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]); 
        byte[] b = new byte[1024];
        while (true) {
          int result = fis.read(b);
          if (result == -1) break;
          String s = new String(b, 0, result);
        } // end while
      } // end try
    // Is this catch strictly necessary?
      catch (FileNotFoundException ex) {
        System.err.println("Could not find file " + args[i]); 
      catch (IOException ex) {
    } // end for

  } // end main


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2003 Elliotte Rusty Harold
Last Modified April 22, 2003