Java Reference
In-Depth Information
Display 10.2
Some Methods of the Class
PrintWriter
(part 2 of 2)
public void
close()
Closes the stream's connection to a file. The following method calls
flush
before closing the file:
public void
flush()
Flushes the output stream. This forces an actual physical write to the file of any data that has been
buffered and not yet physically written to the file. Normally, you should not need to invoke
flush
.
When your program is finished writing to a file, it should
close
the stream connected
to that file. In Display 10.1, the stream connected to the file
stuff.txt
is closed with
the statement
outputStream.close();
The class
PrintWriter
, and every other class for file output or file input streams, has a
method named
close
. When this method is invoked, the system releases any resources
used to connect the stream to the file and does any other housekeeping that is needed.
If your program does not close a file before the program ends, Java will close it for you
when the program ends, but it is safest to close the file with an explicit call to
close
.
Output streams connected to files are often
buffered
, which means that, rather than
physically writing every instance of output data as soon as possible, the data is saved
in a temporary location, known as a
buffer
; when enough data is accumulated in this
temporary location, it is physically written to the file. This can add to efficiency, since
physical writes to a file can be slow. The method
flush
causes a physical write to the file
of any buffered data. The method
close
includes an invocation of the method
flush
.
buffered
buffer
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();
EXAMPLE
outputStream.close();
inputStream.close();
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 automatically 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