import java.io.*; import java.util.*; public class WordCounter { String fileName; int numBytes = 0; int numWords = 0; int numLines = 0; boolean counted = false; String errorMessage = null; public WordCounter(String file) { fileName = file; counted = false; errorMessage = null; } public boolean process() { InputStream in; errorMessage = null; try { in = new FileInputStream(fileName); } catch (Exception e) { errorMessage = "Error opening file: " + fileName + "."; return false; } int byteIn = 0; boolean readNewline = true; boolean readWhitespace = true; try { while ((byteIn = in.read()) >= 0) { char ch = (char)byteIn; // always count bytes. numBytes++; // if we read a newline the last time, // then count a newline. if (readNewline) numLines++; // set for next time. readNewline = (ch == '\n'); // if we are going from whitespace to non-whitespace // then count this word. if (readWhitespace && !Character.isWhitespace(ch)) numWords++; // set this for next time. readWhitespace = Character.isWhitespace(ch); } } catch (IOException e) { errorMessage = "IO Error occured processing file: " + fileName + "."; return false; } counted = true; return true; } public String getErrorMessage() { return errorMessage; } public String toString() { if (errorMessage != null) return "WordCounter: ERROR: " + errorMessage; if (!counted) return "WordCounter: preparing to count: " + fileName; return ("WordCounter: " + fileName + "\n\tbytes\t" + numBytes + "\n\twords\t" + numWords + "\n\tlines\t" + numLines); } public static void main(String [] args) { if (args.length != 1) { System.err.println("USAGE: WordCounter file"); System.exit(-1); } WordCounter wc = new WordCounter(args[0]); wc.process(); System.out.println(wc); } }