Java Reference
In-Depth Information
The third possibility is to use a
FileDescriptor
object that you have obtained by calling the
getFD()
method for an existing
FileInputStream
object, or possibly a
RandomAccessFile
object. For example:
File aFile = new File("C:/Beg Java Stuff/myFile.text");
FileInputStream inputFile1 = null; // Place to store an input stream reference
FileDescriptor fd = null; // Place to store the file descriptor
try {
// Create the stream opened to write
inputFile1 = new FileInputStream(aFile);
fd = inputFile1.getFD(); // Get the file descriptor for the file
} catch(IOException e) { // For IOException or FileNotFoundException
e.printStackTrace(System.err);
System.exit(1);
}
// We can now create another input stream for the file from the file descriptor...
FileInputStream inputFile2 = new FileInputStream(fd);
The
getFD()
method can throw an exception of type
IOException
if an I/O error occurs. Since
IOException
is a superclass of
FileNotFoundException
, the
catch
block will catch either type
of exception.
I'm sure that you noticed that the constructor call that creates
inputFile2
is not in a
try
block. This is not
an oversight. When you create the
FileInputStream
object from a
FileDescriptor
object, the
FileNotFoundException
cannot be thrown since a
FileDescriptor
object always refers to an existing
file. This is because a
FileDescriptor
object can only be obtained from a file stream object that already
encapsulates a connection to a physical file so there can be no doubt that the file is real.
As with the
FileOutputStream
constructors, any of the
FileInputStream
constructors will throw
a
SecurityException
if a security manager exists on the system and read access to the file is not
permitted. Since this is a type of
RuntimeException
you don't have to catch it.
File Channel Read Operations
You obtain a reference to a
FileChannel
object that you can use to read a file by calling the
getChannel()
method of a
FileInputStream
object. Since a
FileInputStream
object opens a
file as read-only, only channel read operations are legal. The channel returned by a
FileInputStream
object has three basic read operations available, each of which read starting at the
byte indicated by the current position in the file. The file position will be incremented by the number of
bytes read. The three
read()
methods for a
FileChannel
object are: