import java.io.*; public class WordCount { public static void main(String[] args) { String fileName = "input.txt"; if (args.length == 1) fileName = args[0]; try { //FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(new FileReader(fileName)); wordCount(br); } catch (IOException e) { e.printStackTrace(); } } static void wordCount(BufferedReader in) { int charCount = 0, spaceCount = 0; int lineCount = 0, wordCount = 0; try { String str; while((str = in.readLine()) != null) { lineCount++; int index = 0; while(index < str.length()) { while(index < str.length() && Character.isWhitespace(str.charAt(index))) { spaceCount++; index++; } if(index < str.length()) wordCount++; while(index < str.length() && !Character.isWhitespace(str.charAt(index))) { index++; charCount++; } } // while for the line } // for the file } catch (IOException e) { e.printStackTrace(); } System.out.println("Chars = " + charCount); System.out.println("Words = " + wordCount); System.out.println("Spaces = " + spaceCount); System.out.println("Lines = " + lineCount); } }