next up previous
Next: Balance checking Up: Assignment 5: Stacks Previous: Assignment 5: Stacks

File I/O

The following program demonstrates basic file input in Java.

import java.io.*;

public class Balance {

  public static void parseLine (String line) {
    System.out.println (line);
  }

  // checkFile: reads each line of the given file and passes it to parseLine
  public static void checkFile (String filename)
                     throws FileNotFoundException, IOException {
    String s;

    // open the file and create a BufferedReader for it
    BufferedReader in =
      new BufferedReader (
         new FileReader (filename));

    // use the BufferedReader to get lines from the file
    while (true) {
      s = in.readLine();
      if (s == null) break;
      parseLine (s);
    }
  }
  
  public static void main (String[] args)
                     throws FileNotFoundException, IOException {
    checkFile ("Balance.java");
  }
}

1.
Type in or cut and paste the above program, and run it. It should print out its own source code file.

2.
Modify this program so that it prints each line backwards. This is easy to do because the elements of a String are indexed and we know how to traverse things backwards.

3.
Modify this program so that it prints the lines in the file in reverse order. This is not as easy to do because the lines we read from a file are not indexed. They are streamed.

One possibility is that we could index the lines of the file by putting them into an array, but we should not assume that we know ahead of time how many lines there are in the file. Thus, a better solution might make use of what the book calls a ``linear data structure.''



Allen B. Downey
1999-10-14