Counting word and chars in a file in java

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.

 

/*Counting word and chars in a file*/

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;

//to skipp counting on initial space and empty line

if((i=fis.read())==32 || i==13 )

wcount--;

while((i=fis.read()) !=-1)

{

//ASCII value of space is 32

//ASCII value of line break 10

//ASCII value of empty line 13

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

Ebook Download
View all
Learn
View all