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.
- import java.io.*;
- import java.util.*;
- public class WordCount
- {
- public static void main(String arg[]) throws Exception
- {
- Scanner sc = new Scanner(System.in);
- System.out.print("Provide file name:");
- String fname = sc.next();
- FileReader fis = new FileReader(fname);
- int wcount = 0, ccount = 1;
- boolean flag = false;
- int i = 0;
- if ((i = fis.read()) == 32 || i == 13)
- wcount--;
- while ((i = fis.read()) != -1)
- {
- if (i == 32 || i == 10 || i == 13)
- {
- while (i == 32 || i == 10 || i == 13)
- {
- i = fis.read();
- ccount++;
- System.out.println(i);
- }
- wcount++;
- }
- ccount++;
- }
- System.out.println("Words " + (++wcount));
- System.out.println("Chars " + ccount);
- }
- }
Compile
Javac
WordCount.java
Java.
WordCount