import java.io.BufferedReader; import java.io.IOException; // ------------------------------------------------------------------------- /** * This class provides basic line- and character-counting behavior for * buffered reader input sources. The object keeps a running total * over all input sources that have been counted. * * @author Stephen Edwards * @version Feb 22, 2005 */ public class LineCounter { //~ Instance/static variables ............................................. private int lines = 0; private int chars = 0; //~ Constructor ........................................................... // ---------------------------------------------------------- /** * Creates a new LineCounter object. */ public LineCounter() { // no action needed } //~ Methods ............................................................... // ---------------------------------------------------------- /** * Getter for the lines property. * @return the current line count */ public int lines() { return lines; } // ---------------------------------------------------------- /** * Getter for the characters property. * @return the current character count */ public int characters() { return chars; } // ---------------------------------------------------------- /** * Consume all the input from the given input source, counting the * number of lines and characters read in. The counts for this * stream are added to the running totals stored in this line counter * object. * @param in the stream to read from * @throws IOException if there is an error reading from the stream */ public void count( BufferedReader in ) throws IOException { lines = 0; chars = 0; String line = in.readLine(); while ( line != null ) { ++lines; chars += line.length(); line = in.readLine(); } } // ---------------------------------------------------------- /** * Open the given file and count the number of lines and characters * it contains. The counts for this file are added to the running * totals stored in this line counter object. * @param fileName the name of the file to count */ public void countFile( String fileName ) { try { BufferedReader in = new BufferedReader( new java.io.FileReader( fileName ) ); count( in ); in.close(); } catch ( IOException e ) { e.printStackTrace(); } } // ---------------------------------------------------------- /** * Open the given URL and count the number of lines and characters * it contains. The counts for this URL are added to the running * totals stored in this line counter object. * @param url the web page to count */ public void countURL( String url ) { try { BufferedReader in = new BufferedReader( new java.io.InputStreamReader( new java.net.URL( url ).openStream() ) ); count( in ); in.close(); } catch ( IOException e ) { e.printStackTrace(); } } }