(^214) | File Objects and Looping Statements
Disk file
outfile.dat
Disk file
infile.dat
BufferedReader
dataFile
FileReader inFile
readLine
read
skip
close
Added methods:
Methods:
PrintWriter
payFile
print
println
Added methods:
FileWriter outFile
write
flush
close
Methods:
Figure 5.2 Relationships between FileWriterand PrintWriter, and between FileReaderand BufferedReader
Declare the File Identifier In Java, you declare file identifiers in the same way that you declare any
variable—you specify the class and then the name:
PrintWriter outFile;
BufferedReader inFile;
Note that BufferedReaderis used for input files only, and PrintWriteris used for
output files only. With these classes, you cannot read from and write to the same
file. These classes work with what Java calls character stream files. In a later chap-
ter, we will encounter other kinds of files that allow us to output and input whole
objects. The advantage of a character stream file is that we work with this kind of
file in the editor. Thus, we can prepare an input file with the editor, process it with
an application, and then view the output with the editor.
The data in character stream files are organized into lines. A line is a string of charac-
ters that ends with a special character called an end-of-line (EOL) mark. When you examine
such a file with an editor, each line in the file appears as a line of text on the screen. The ed-
itor doesn’t display the EOL mark. Rather, the EOL mark simply tells the editor when to go
to the next line as it places the characters on the screen.
Character stream file A file
that is stored as a sequence of
characters