Programming and Problem Solving with Java

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

Once a file is closed, it can again be assigned to a file object with a call to new. For exam-
ple, if the file infile.datis associated with the file object inFile, we can write the following:


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


The effect of these two statements is to temporarily break the association between the disk
file (infile.dat) and the file identifier (inFile), and then to restore their connection. A side
effect of these operations is that the file pointer is reset to the beginning of the file as part
of the constructor call. After the call to close, it would also be possible to assign a different
disk file to inFileor to assign infile.datto a different file identifier. Here’s an example that
does both:


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


An Example Application Using Files


Now let’s pull our discussion of file I/O together by writing a simple application. The appli-
cation should read three lines from an input file, display each line on System.out, and write
the lines in reverse order onto an output file. We use BufferedReaderand PrintWriterfile ob-
jects that we associate with files called infile.datand outfile.dat. Let’s name the three
lines of input lineOne,lineTwo, and lineThree. Because readLinereturns a string, we can invoke
it as we instantiate each stringobject. Once the lines have been read, we close the input file.


importjava.io.*; // File classes
public classUseFile
{
public static voidmain(String[] args) throwsIOException
{
PrintWriter outFile; // Output data file
BufferedReader inFile; // Input data file
String lineOne; // Strings to hold data lines
String lineTwo;
String lineThree;
// Prepare input and output files
inFile = new BufferedReader(new FileReader("infile.dat"));
outFile = new PrintWriter(new FileWriter("outfile.dat"));
// Read in three lines from infile.dat
lineOne = new String(inFile.readLine());
lineTwo = new String(inFile.readLine());
lineThree = new String(inFile.readLine());
inFile.close(); // Finished reading
// Write three lines to screen
System.out.println(lineOne);
System.out.println(lineTwo);

Free download pdf