Java Reference
In-Depth Information
Handling Exceptions
Several exceptions in the
java.io
package might occur when you are working with files
and streams.
A
FileNotFound
exception occurs when you try to create a stream or file object using a
file that couldn't be located.
An
EOFException
indicates that the end of a file has been reached unexpectedly as data
was being read from the file through an input stream.
These exceptions are subclasses of
IOException
. One way to deal with all of them is to
enclose all input and output statements in a
try
-
catch
block that catches
IOException
objects. Call the exception's
toString()
or
getMessage()
methods in the
catch
block to
find out more about the problem.
All byte streams are a subclass of either
InputStream
or
OutputStream
. These classes
are abstract, so you cannot create a stream by creating objects of these classes directly.
Instead, you create streams through one of their subclasses, such as the following:
FileInputStream
and
FileOutputStream
—Byte streams stored in files on disk,
CD-ROM, or other storage devices
n
DataInputStream
and
DataOutputStream
—A filtered byte stream from which data
such as integers and floating-point numbers can be read
n
InputStream
is the superclass of all input streams.
File Streams
The byte streams you'll work with most often are likely to be file streams, which are
used to exchange data with files on your disk drives, CD-ROMs, or other storage devices
you can refer to by using a folder path and filename.
You can send bytes to a file output stream and receive bytes from a file input stream.
File Input Streams
A file input stream can be created with the
FileInputStream(
String
)
constructor. The
String
argument should be the name of the file. You can include a path reference with
the filename, which enables the file to be in a different folder from the class loading it.
The following statement creates a file input stream from the file
scores.dat
:
FileInputStream fis = new FileInputStream(“scores.dat”);