(^212) | File Objects and Looping Statements
Figure 5.1 Disks Used for File Storage
5.1 File Input and Output
In everything we’ve done so far, we’ve assumed that input occurs via the screen. We have read
input typed on the screen and sent messages to the screen. We look now at input/output (I/O)
using files.
Files
Earlier we defined a fileas a named area in secondary storage that holds a collection of in-
formation (for example, the Java code we have typed into the editor). The information in a
file usually is stored on an auxiliary storage device, such as a disk (see Figure 5.1).
Reading and writing data on files is similar to input and output on the screen, but it dif-
fers in some important ways. A file contains a sequence of values, and it has a distinct be-
ginning and end—that is, a first value and a last value. You may think of reading a file as
analogous to reading a book in that it is read from the front to the back. Just as you might
use a bookmark to keep track of your place in a book, Java uses a file pointerto remember its
place in a file. Each time some data are read from the file, the file pointer advances to the point
where reading should resume next. Each read operation copies a value from the file into a
variable in the code and advances the file pointer. A series of read operations eventually
reaches the last value in the file, and the pointer is then said to be at end-of-file (EOF).
Writing data on a file is like writing in an empty notebook. At the beginning, the file is
empty. Then data are written onto it from front to back. The file pointer always indicates the
end of the last value written so that writing can resume after that point. In effect, the file