5.1 File Input and Output | 213
pointer is always at EOF when a file is being written. The size of the file increases with each
write operation. The only limit placed on the size of a file is the amount of disk space avail-
able to the application.
Why would we want an application to read data from a file instead of the user interface?
If an application will read a large quantity of data, it is easier to enter the data into a file with
an editor than to enter it while the application is running. With the editor, we can go back
and correct mistakes. Also, we do not have to enter the data all at once; we can take a break
and come back later. If we want to rerun the application at some point, having the data
stored in a file allows us to do so without retyping the data.
Why would we want the output from an application to be written to a disk file? The con-
tents of a file can be displayed on a screen or printed. This ability gives us the option of look-
ing at the output over and over again without having to rerun the application. Also, the
output stored in a file can be read into another application as input. For example, an appli-
cation that calculates a payroll could write its output to a file that could then be input to an
application that prints checks.
Using Files
If we want an application to use file I/O, we have to do five things:
1.Import the library package java.io.*.
2.Use declaration statements to declare the file variable identifiers we will use.
3.Instantiate each file object.
4.Use methods associated with the file object to read or write it.
5.Call a method to close the file when we are done with it.
Import the Package java.io.* The first thing we must do is import the package containing the
classes that define a file:
import java.io.*;
Through the packagejava.io.*, Java defines many classes for different forms of I/O. In the
case of our applications, we use just four of these classes:FileReader,FileWriter,BufferedReader,
andPrintWriter. TheFileReaderandFileWriterclasses are like theInputStreamReaderclass that
we’ve been using withSystem.in. We won’t use them directly, but we do need them as part of
instantiating theBufferedReaderandPrintWriterclasses. The reason is that the Java library
builds the abstraction for the file classes in layers. TheFileReaderandFileWriterclasses pro-
vide only the basic file object functionality of reading and writing one character at a time. On
top of this abstraction, Java builds another layer of objects that are more convenient for in-
put and output of different kinds of data. Figure 5.2 shows the relationships among these
classes. We explore how we can create our own Java layering of abstractions in Chapter 7.
PrintWriteris the file class that is most similar to System.out. Of course, we’ve been us-
ing BufferedReaderon top of System.inall along, and now we see how to apply it to a file.
Thus, many of the operations that we use with files should already be familiar to you.