Java Streams  «Prev  Next»

Processing Streams - Exercise Result

You Said:
How do you deal with processing streams in a Java program when you can't control how fast the bytes are coming or you do not know how long the stream is? The key to processing the stream is a while loop that processes each piece of data until you encounter the end-of-stream or some other exceptional condition occurs. The main() routine simply gets the file names from the command line and calls the countLines() routine to process each name. Since any errors are handled in the countLines() routine, the main program will continue after an error occurs while trying to process one of the files.

import java.io.*;
public class LineCounts {
 public static void main(String[] args) {
  if (args.length == 0) {
   /* This program must have at least one command-line argument to work with. */
   System.out.println("Usage:   java LineCounts < file-names>");
     return;
   }
   for (int i = 0; i < args.length; i++) {
     System.out.print(args[i] + ": ");
     countLines(args[i]);
   }
 }  // end main()
  static void countLines(String fileName) {
   /* Count the number of lines in the specified file, and print the number to standard output.  
   If an error occurs while processing the file, print an error message instead.
    Two try...catch statements are used so I can give a different error message in each case. */
    TextReader in;  // A stream for reading from the file.
    int lineCount;  // Number of lines in the file.
    try {
      in = new TextReader( new FileInputStream(fileName) );
    }
    catch (Exception e){
      System.out.println("Error.  Can't open file.");
      return;
    }
    lineCount = 0;
    try {
        while (in.peek() != '\0') {
               // Read the next line and count it.
           in.getln();
           lineCount++;
        }
     }
     catch (Exception e) {
        System.out.println("Error.   Problem with reading from file.");
        return;
     }
     System.out.println(lineCount);
   }  // end countLines()         
 } // end class LineCounts