Java Reference
In-Depth Information
Note that, in spite of the name, the files that you create by using the
createTempFile()
method are
not necessarily temporary, as they will not be deleted automatically. You must use
delete()
or
deleteOnExit()
to ensure that files you no longer require are removed.
You can arrange for a temporary file to be deleted automatically at the end of the program by calling
the
deleteOnExit()
method for the
File
object. For example, you might write:
File tempFile = File.createTempFile("list", null);
tempFile.deleteOnExit();
The first statement will create a temporary file with a name of the form
listxxxxx.tmp
in the default
temporary directory. The
xxxxx
part of the name is generated automatically. Since we did not supply a
suffix
, the file extension will be
.tmp
by default. The second statement calls the
deleteOnExit()
method for
tempFile
, so we are assured that this file won't be left lying around after the program
finishes. You can apply the
deleteOnExit()
method to any
File
object, not just those
corresponding to temporary files, but do so with caution. As noted above, the delete is irrevocable once
you have called the method!
We will be trying out some of these methods in examples later in this chapter. Now we understand how
to define objects encapsulating a path in a Java program, we can move on to creating file stream objects.
We will look at file output streams first.
Creating File Output Streams
You use a
FileOutputStream
object when you want to write to a physical file on a disk. The
FileOutputStream
class is derived from the
OutputStream
class and therefore inherits the
methods of that class for writing to a file. However, we won't bother going into detail on these, or the
versions in the
FileOutputStream
class that override them, as we will be using the new file channel
capability to write to a file.
There are five constructors for
FileOutputStream
objects:
Constructor
Description
FileOutputStream
(String filename)
Creates an output stream for the file
filename
. The existing
contents of the file will be overwritten. If the file cannot be
opened for any reason, an exception of type
FileNotFoundException
will be thrown.
FileOutputStream
(String filename,
boolean append)
Creates an output stream for the file
filename
. Data written to
the file will be appended following the existing contents if
append
is
true
. If append is
false
any existing file contents
will be overwritten. If the file cannot be opened for any reason,
an exception of type
FileNotFoundException
will be
thrown.