Java Reference
In-Depth Information
Constructor
Description
FileOutputStream
(File file)
Creates a file output stream for the file represented by the object
file . Any existing file contents will be overwritten. If the file
cannot be opened, an exception of type
FileNotFoundException will be thrown.
FileOutputStream
(File file,
boolean append)
Creates a file output stream for the file represented by the object
file . 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 writing for any reason, an exception of type
FileNotFoundException will the thrown.
FileOutputStream
(FileDescriptor
desc)
Creates an output stream corresponding to the argument desc .
A FileDescriptor object represents an existing connection to
a file so, since the file must exist, this constructor does not throw
an exception of type FileNotFoundException .
The first four constructors will also create the file if it does not already exist, but only if the parent
directory exists, so it is a good idea to check this. All of these constructors can throw a
SecurityException if writing to the file is not authorized on your system, although by default there
is no security manager for an application in which case there are no restrictions on writing files. Once
you have created a FileOutputStream object, the physical file is automatically opened, ready to be
written. Once you have written the file, using a channel as we shall see in Chapter 10, you can close the
file by calling the close() method for the FileOutputStream object. This also closes the file
channel and releases all system resources associated with the stream.
To create a stream object of type FileOutputStream , you will typically create a File object first,
and then pass that to a FileOutputStream constructor. This approach enables you to check the
properties of the file using the File object before you try to create the stream and thus, avoid potential
problems. Of course, you can create a FileOutputStream object directly from a String object that
defines the path and file name, but it is generally much less convenient to do this. We will come back to
the third possibility - creating a file stream object from a FileDescriptor object - in a moment.
In passing, here is how you would create a file output stream directly from the file name:
FileOutputStream outputFile = null; // Place to store the stream reference
try {
outputFile = new FileOutputStream("myFile.txt");
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
}
Search WWH ::




Custom Search