Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.1 File Input and Output | 215

Instantiate the File Objects The third thing we have to do is to instantiate the file objects. Part of


instantiating a file object involves telling the operating system the name of the file on the
disk. Thus, we pass the file’s name on the disk to the constructor for the object. That way, the
JVM and operating system know which disk file to use when the code performs an operation
on the file. As we’ve done with System.in, we nest the instantiation of the simpler class in-
side of the class that we actually use. Here’s what we’ve been doing:


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


In using BufferedReaderwith a file, we write the following instead:

inFile = new BufferedReader(new FileReader("infile.dat"));


where the operating system uses the string "infile.dat"to identify the actual disk file we
wish to use. We instantiate a PrintWriterin much the same way. For example, we can write
the following statement:


outFile = new PrintWriter(new FileWriter("outfile.dat"));


Exactly what do these statements do? The constructors create file objects for use in your
code and associate them with physical files on disk. The object is then assigned to a file
variable that you can reference in other statements in your code. The first statement creates
a connection between the file variable inFileand the disk file named infile.dat. (Names of
file variables must be Java identifiers,
but many computer systems do not
use Java syntax for file names on disk.
For example, file names can include
dots and slashes (/) but file variable
identifiers cannot.) Similarly, the sec-
ond statement associates the identi-
fier outFile with the disk file
outfile.dat.
The constructor performs addi-
tional operations depending on
whether the file is an input file or an
output file. With an input file, the con-
structor places the file pointer at the
first piece of data in the file. (Each in-
put file has its own file pointer.) With
an output file, the constructor checks
whether the file already exists. If the
file doesn’t exist, it creates a new
empty file. If the file does exist, it
erases the old contents of the file. Then
the file pointer is placed at the begin-
ning of the empty file (see Figure 5.3).


File infile after the call
to the constructor

File outfile after the call
to the constructor
inFile outFile
File
pointer

File
pointer

Operating system
file name:
outfile.dat

Operating system
file name:
infile.dat

Figure 5.3 The Effect of Calling a Constructor for a Character Stream File Object
Free download pdf