Counting word and chars in a file in java

By Satyapriya Nayak Sep 23, 2011
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.

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

Satyapriya Nayak

Satyapriya Nayak is a software developer from Bhubaneswar, India. He holds a Bachelor's degree in Electronics and telecommunication and is an active member of C# Corner. 

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs