Course Links

Exercises

Resources

External

Reading from an External File

Reading from an external file in Java is nearly as simple as reading from the standard input. Recall that in order to read data from standard input, we needed to create a BufferedReader attached to System.in:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

With an external file, we can create a BufferedReader in nearly the same way, only it is attached to the file. We must know the name of the file in order to do this.

BufferedReader file = new BufferedReader(new FileReader("MyFile"));

It is possible that MyFile does not exist, which would result in an exception. To handle this we would normally wrap the creation of the FileReader in a try/catch block:

        String fname = "MyFile.txt";
        BufferedReader file = null;
        try {
            file = new BufferedReader(new FileReader(fname));
        } catch (IOException e) {
            System.err.println("Problem reading file "+fname);
            System.exit(-1);
        }

This is a fairly simple yet general form which should work for a variety of applications. If you need to open several files, you can wrap them all in the same try/catch block. Don't forget that all of this requires that you input the java.io package.

Recall that another way for a program to read an external file is to send that file to the standard input using Unix input redirection. A separate tutorial covers this subject.

Exercise

Write a program that takes two files names as command line arguments. It should compare the two files, reading them line by line, and say whether their contents are the same, or different.

Writing to an External File

Take a look at WriteEmployeesAsText.java. It demonstrates methods for writing data to an external file, including formatted output. You'll also need Employee.java to store the data.

javac Employee.java WriteEmployeesAsText.java
java WriteEmployeesAsText employees.txt
more employees.txt

Binary Files

The file employees.txt produced above is a text file. You can open it up in emacs and see what it contains. The examples in this section, by contrast, store data in a binary file, meaning that the data are in a format similar to that used internally in memory. Usually this will result in a smaller file size and faster read/write times. Take a look at ConvertTextToBinary.java, which reads the text file and writes the same data out again as a binary file. Then look at ReadBinaryFile.java, which reads the binary file in again and prints the result to the terminal.

javac ConvertTextToBinary.java ReadBinaryFile.java
java ConvertTextToBinary employees.txt employees.bin
more employees.bin
java ReadBinaryFile employees.bin

A final note: text and binary files may be named anything you like; the name by itself does not affect the format. But using the .txt and .bin is a convention that helps keep things straight.