Java Reference
In-Depth Information
Closing a File
When your program is finished writing to a file or reading from a file, it should close the
stream connected to that file by invoking the method named close .
SYNTAX
Stream_Object .close();
EXAMPLES:
outputStream.close();
inputStream.close();
the file of any buffered data. The method close includes an invocation of the method
flush .
It may seem like there is no reason to use the method close to close a file. If
your program ends normally but without closing a file, the system will automati-
cally close it for you. So why should you bother to close files with an explicit call
to the method close ? There are at least two reasons. First, if your program ends
abnormally, then Java may not be able to close the file for you. This could dam-
age the file. In particular, if it is an output file, any buffered output will not have
been physically written to the file. So the file will be incomplete. The sooner you
close a file, the less likely it is that this will happen. Second, if your program
writes to a file and later reads from the same file, it must close the file after it is
through writing to the file and then reopen the file for reading. (Java does have a
class that allows a file to be opened for both reading and writing, which we will
discuss in Section 10.5.)
PITFALL: A try Block Is a Block
Notice that in Display 10.1 we declare the variable outputStream outside of the try
block. If you were to move that declaration inside the try block, you would get a
compiler error message. Let's see why.
Suppose you replace
PrintWriter outputStream = null ;
try
{
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
}
Search WWH ::




Custom Search