Counting number of words in a file

I'm having a problem counting the number of words in a file. The approach that I am taking is when I see a space or a newLine then I know to count a word.

The problem is that if I have multiple lines between paragraphs then I ended up counting them as words also. If you look at the readFile() method you can see what I am doing.

Could you help me out and guide me in the right direction on how to fix this?

Example input file (including a blank line):

word word word
word word

word word word


I would change your approach a bit. First, I would use a BufferedReader to read the file file in line-by-line using readLine(). Then split each line on whitespace using String.split("\\s") and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).

You can use a Scanner with a FileInputStream instead of BufferedReader with a FileReader. For example:-

File file = new File("sample.txt");
Scanner sc = new Scanner(new FileInputStream(file));
int count=0;
System.out.println("Number of words: " + count);

Need Your Help

Maximizing the size of the content div in jQueryMobile

css mobile-website mobile-browser

How can I maximize the size of the div that plays the role of "content"?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.