Displaying number of Characters, Lines &
Words in a file

Aim: 
To write a java program that displays the number of characters, lines and words in a text file.

Description:
The FileInputStream class creates an InputStream that we can use to read bytes from a file.When a FileInputStream is created, it is opened for reading. Take three variables of type int and initialize it with zero for counting number of characters, words and lines. Read the contents from file character by character and increment character count by 1 for each character. Whenever a new line character is encountered then increment line count by 1. Whenever a space is encountered then increment word count by 1.

Program:
import java.io.*;
class FileStat
{ public static void main(String args[]) throws IOException
{ int pre=' ' , ch , ctr=0 , L=0 , w=1;
String fname;
BufferedReader br=new BufferedReader(new InputStreamReader (
System.in));
System.out.print("Enter a file name: ");
fname=br.readLine();
FileInputStream fin = new FileInputStream(fname);
while((ch=fin.read())!=-1)
{
//char count
if(ch!=' ' && ch!='\n')
ctr++;
//line count
if(ch=='\n')
L++;
//word count
if(ch==' ' && pre!=' ')
w++;
pre=ch;
}
System.out.println("Char count="+ctr);
System.out.println("Word count="+(w+(L-1))); System.out.println("Line count="+L);
}
}