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");
}
}
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.''