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.FileNotFoundException;
- 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 Map<String, Integer> addWord(Map<String, Integer> words, String word) {
- // :NOTE: without if, use .getOrDefault() method
- if (words.containsKey(word)) {
- words.replace(word, words.get(word), words.get(word) + 1);
- } else {
- if (word.length() > 0) {
- words.put(word, 1);
- }
- }
- return words;
- }
- 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 {
- // :NOTE: Map is passed by reference
- words = addWord(words, word.toString().toLowerCase());
- word.delete(0, word.length());
- }
- read = reader.read();
- symbol = (char) read;
- }
- // :NOTE: same
- words = addWord(words, word.toString().toLowerCase());
- // :NOTE: FileNotFoundException can't appear here
- } catch (FileNotFoundException e) {
- System.out.println(e.getMessage());
- } finally {
- reader.close();
- }
- // :NOTE: IOException can catch not only "file not found"
- } catch (IOException e) {
- System.out.println("Input File Not Found: " + e.getMessage());
- }
- // :NOTE: put this block of code in first "try", why do you separate them?
- 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());
- // :NOTE: put lineSeparator in the previous .write() call, why do you separate them?
- writer.write(System.lineSeparator());
- }
- } catch (FileNotFoundException e) {
- System.out.println("Output File Not Found: " + e.getMessage());
- } finally {
- writer.close();
- }
- // :NOTE: same
- } catch (IOException e) {
- System.out.println("Output File Not Found: " + e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement