Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- import java.io.Reader;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.FileOutputStream;
- import java.lang.String;
- import java.util.LinkedHashMap;
- import java.util.Map;
- public class WordStatInput {
- public static void addWord(Map<String, Integer> words, String word) {
- if (word.length() > 0) {
- // :NOTE: extra action -- read documentation about Map and .putIfAbsent()
- words.putIfAbsent(word, words.getOrDefault(word, 0));
- words.replace(word, words.get(word), words.get(word) + 1);
- }
- }
- public static void main(String[] args){
- Map<String, Integer> words = new LinkedHashMap<>();
- try {
- Reader reader = new BufferedReader(new InputStreamReader(
- new FileInputStream(args[0])
- ));
- try {
- char symbol;
- StringBuilder word = new StringBuilder();
- int read = reader.read();
- symbol = (char) read;
- while (read > -1) {
- if (Character.isLetter(symbol) || symbol == '\'' || Character.DASH_PUNCTUATION == Character.getType(symbol)) {
- word.append(symbol);
- } else {
- addWord(words, word.toString().toLowerCase());
- word.delete(0, word.length());
- }
- read = reader.read();
- symbol = (char) read;
- }
- addWord(words, word.toString().toLowerCase());
- } finally {
- reader.close();
- }
- // :NOTE: you already catch IOException, why do you add "try" here?
- try {
- BufferedWriter writer = new BufferedWriter(
- new OutputStreamWriter(
- new FileOutputStream(args[1])
- )
- );
- try {
- for (Map.Entry<String, Integer> output : words.entrySet()) {
- writer.write(output.getKey() + " " + output.getValue() + System.lineSeparator());
- }
- } finally {
- writer.close();
- }
- } catch (IOException e) {
- System.out.println("I/O Exception: " + e.getMessage());
- }
- // :NOTE: it's better to clarify the exception with the file missing to the user, if it occurs
- } catch (IOException e) {
- System.out.println("I/O Exception: " + e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement