Examples of Input from Files

You create a new FileInputStream object by passing the name of the file to the constructor, like this:

FileInputStream fis = new FileInputStream("14.html");

This throws a FileNotFoundException, a subclass of IOException, if the named file can't be located. Generally Java looks for files in the current working directory. This is not necessarily the same directory where the .class file is located.

The following simple application reads the files named on the command line and prints them on System.out.

import java.io.*;


public class Type {

  public static void main(String[] args) {
  
    for (int i = 0; i < args.length; i++) {
      try {
        FileInputStream fis = new FileInputStream(args[i]); 
        int n;     
        while ((n = fis.available()) > 0) {
          byte[] b = new byte[n];
          int result = fis.read(b);
          if (result == -1) break;
          String s = new String(b);
          System.out.print(s); 
        } // end while
        fis.close();
      } // end try
    // Is this catch strictly necessary?
      catch (FileNotFoundException e) {
        System.err.println("Could not find file " + args[i]); 
      }
      catch (IOException e) {
        System.err.println(e); 
      }
      System.out.println();
    } // end for

  } // end main

}

Previous | Next | Top
Last Modified July 8, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu