/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * WordCount.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 3-3: * Write a program that counts and reports the number of lines, words and * characters in a specified file. Use static methods of the java.lang.Character * class to determine whether a given character is a space (and therefore the * boundry between two words). * * @author Matthew Feldt * @version 1.0, 01/30/2001 9:29 */ package com.feldt.examples.io; import java.io.*; public class WordCount { private static int lineCount, wordCount, charCount; /** Sole WordCount constructor. */ WordCount(File f) throws IOException, IllegalArgumentException { count(f); } /** * Static method to count the number of lines, words and characters in a * file. */ public static String count(File f) throws IOException, IllegalArgumentException { lineCount = wordCount = charCount = 0; boolean inWhiteSpace = true; int ch; BufferedReader in; // confirm file is readable, regular and exists if (! f.exists()) throw new IllegalArgumentException(f.getName() + ": no such file or directory."); if (! f.canRead()) throw new IllegalArgumentException(f.getName() + ": read protected."); if (! f.isFile()) throw new IllegalArgumentException(f.getName() + ": not a regular file."); in = new BufferedReader(new FileReader(f)); while ((ch = in.read()) != -1) { charCount++; // increment charCount for every character if (Character.isWhitespace((char)ch)) { inWhiteSpace = true; // increment lineCount if ch is newline if (ch == '\n') lineCount++; } else if (inWhiteSpace) { // mark words through state changes in inWhiteSpace wordCount++; inWhiteSpace = false; } } return f.getName() + ": " + lineCount + " lines, " + wordCount + " words, " + charCount + " characters."; } public int getLineCount() { return lineCount; } public int getWordCount() { return wordCount; } public int getCharCount() { return charCount; } /** test class */ static class Test { public static void main (String args[]) { for (int i = 0; i < args.length; i++) { try { // call WordCount.count() for each file on the command line System.out.println(WordCount.count(new File(args[i]))); /* could also have done the following WordCount wc = new WordCount(new File(args[i])); System.out.println(args[i] + ": " + wc.getLineCount() + " lines, " + wc.getWordCount() + " words, " + wc.getCharCount() + " characters."); */ } catch(IOException e) { System.err.println(e.getMessage()); } catch(IllegalArgumentException e) { System.err.println(e.getMessage()); } } } } }