Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^218) | File Objects and Looping Statements
Likewise, an integer value can be read as shown here:
int intNumber;
intNumber = Integer.parseInt(dataFile.readLine());
Reading data from a file does notdestroy the data on the file. Because the file pointer
moves in just one direction, however, we cannot go back and reread data that has been read
from the disk file unless we return the pointer to the beginning of the file and start over. As
we will see in the next section, closing a file and reassigning it to a file object with newcauses
the file pointer to return to the beginning of the file.
Another method associated with objects of the classBufferedReaderis calledskip. When we
pass alongvalue toskip, it causes the file pointer to skip over that many characters in the file.
Recall that we write a literal value of typelongwith anLat the end. For example, the statement
inFile.skip(100L);
skips the next 100 characters in the file. Reading can then resume at the new file pointer’s
position. If skipreaches EOF before it has skipped the specified number of characters, then
the application halts with an error message because an IOExceptionis thrown. When we put
all of this together in an application, we see that, just as happened when we used System.in,
file input requires us to include the throwsIOExceptionclause in the heading for main; it lets
Java know that such an exception should be passed to the JVM. The FileWriterclass similarly
includes methods that can throw an IOException. Thus, for any application that uses file I/O,
the heading for mainshould include the throwsclause.
public static voidmain(String[] args) throwsIOException
We will return to the subject of reading data from files later in this chapter. Except for
some trivial cases, we must combine reading operations with loops to read through all of the
data on a file.


Call a Method to Close the File When Done with It After we have finished reading from or writing to a


file, we must close the file. Closing a file tells the operating system that we no longer need
the file, and it makes the file available for use by another application. Once a file is closed,
it is no longer associated with the corresponding identifier in our code. Each of the file classes
that we have discussed in this chapter has a void method called closeassociated with it. The
closemethod does not take any arguments. The following code segment closes the files that
we have been using in our discussions:

inFile.close();
outFile.close();

Although most Java systems automatically close every file when an application exits, it
is good programming practice to explicitly close each file. Also, once an application has fin-
ished using a file, it should be closed immediately. You don’t have to wait until the end of an
application to close a file.
Free download pdf