.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Melody Anderson

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Counting word and chars in a file in java

Posted By:satyapriyanayak       Posted Date: July 07, 2014    Points: 40    Category: Javascript    URL: http://www.dotnetspark.com  

In this Code Snippets 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 )


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)









System.out.println("Words "+(++wcount));

System.out.println("Chars "+ccount);




Javac WordCount.java

Java WordCount


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend