Program 20.3 cat

Program 20.3 implements the Unix cat utility through Java. That is it accepts a series of file names on the command line and prints those files to the standard output in the order they were listed.

import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;

class cat  {

  public static void main (String args[]) {
  
  String thisLine;

  //Loop across the arguments
  for (int i=0; i < args.length; i++) {
 
  //Open the file for reading
  try {
    FileInputStream fin =  new FileInputStream(args[i]);

    // now turn the FileInputStream into a DataInputStream
    try {
      DataInputStream myInput = new DataInputStream(fin);
  
      try {
        while ((thisLine = myInput.readLine()) != null) {  
          System.out.println(thisLine);
        } // while loop ends here
      }
      catch (Exception e) {
       System.err.println("Error: " + e);
      }
    } // end try
    catch (Exception e) {
      System.err.println("Error: " + e);
    }
  
   } // end try
   catch (Exception e) {
    System.err.println("failed to open file " + args[i]);
    System.err.println("Error: " + e);
  }
  } // for end here
  
  } // main ends here

}

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home