Advertisement
alyoshinkkaa

Untitled

Aug 1st, 2023
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileInputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.Reader;
  6. import java.io.IOException;
  7. import java.io.OutputStreamWriter;
  8. import java.io.FileOutputStream;
  9. import java.io.FileNotFoundException;
  10. import java.lang.String;
  11. import java.util.LinkedHashMap;
  12. import java.util.Map;
  13.  
  14. public class WordStatInput {
  15. public static void addWord(Map<String, Integer> words, String word) {
  16. if (word.length() > 0) {
  17. // :NOTE: extra action
  18. words.putIfAbsent(word, 0);
  19. // :NOTE: use getOrDefault instead of putIfAbsent and replace
  20. words.replace(word, words.get(word), words.get(word) + 1);
  21. }
  22. }
  23. public static void main(String[] args){
  24. Map<String, Integer> words = new LinkedHashMap<>();
  25. try {
  26. Reader reader = new BufferedReader(new InputStreamReader(
  27. new FileInputStream(args[0])
  28. ));
  29. try {
  30. char symbol;
  31. StringBuilder word = new StringBuilder();
  32. int read = reader.read();
  33. symbol = (char) read;
  34. while (read > -1) {
  35. if (Character.isLetter(symbol) || symbol == '\'' || Character.DASH_PUNCTUATION == Character.getType(symbol)) {
  36. word.append(symbol);
  37. } else {
  38. addWord(words, word.toString().toLowerCase());
  39. word.delete(0, word.length());
  40. }
  41. read = reader.read();
  42. symbol = (char) read;
  43. }
  44. addWord(words, word.toString().toLowerCase());
  45. } finally {
  46. reader.close();
  47. }
  48. BufferedWriter writer = new BufferedWriter(
  49. new OutputStreamWriter(
  50. new FileOutputStream(args[1])
  51. )
  52. );
  53. try {
  54. for (Map.Entry<String, Integer> output : words.entrySet()) {
  55. writer.write(output.getKey() + " " + output.getValue() + System.lineSeparator());
  56. }
  57. } finally {
  58. writer.close();
  59. }
  60. } catch (FileNotFoundException e) {
  61. System.out.println("File not found: " + e.getMessage());
  62. } catch (IOException e) {
  63. System.out.println("I/O Exception: " + e.getMessage());
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement