Introduction

In this blog we will know how to count word and chars in a file. Store the txt file in the context folder and enter the file name in the console after compiling the program.
  1. import java.io.*;
  2. import java.util.*;
  3. public class WordCount
  4. {
  5. public static void main(String arg[]) throws Exception
  6. {
  7. Scanner sc = new Scanner(System.in);
  8. System.out.print("Provide file name:");
  9. String fname = sc.next();
  10. FileReader fis = new FileReader(fname);
  11. int wcount = 0, ccount = 1;
  12. boolean flag = false;
  13. int i = 0;
  14. if ((i = fis.read()) == 32 || i == 13)
  15. wcount--;
  16. while ((i = fis.read()) != -1)
  17. {
  18. if (i == 32 || i == 10 || i == 13)
  19. {
  20. while (i == 32 || i == 10 || i == 13)
  21. {
  22. i = fis.read();
  23. ccount++;
  24. System.out.println(i);
  25. }
  26. wcount++;
  27. }
  28. ccount++;
  29. }
  30. System.out.println("Words " + (++wcount));
  31. System.out.println("Chars " + ccount);
  32. }
  33. }

Compile

Javac WordCount.java
Java. WordCount