Blog

Counting word and chars in a file in java

Posted by Satyapriya Nayak Blogs | Java 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

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.
Employers - Post Free Jobs
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
Employers - Post Free Jobs