Java Reference
In-Depth Information
and Java provides methods to read and write bytes from and to a file. Thus, reading and
writing files using byte streams is very common. However, Java allows you to wrap a byte-
oriented file stream within a character-based object, which is shown later in this chapter.
To create a byte stream linked to a file, use
FileInputStream
or
FileOutputStream
. To
open a file, simply create an object of one of these classes, specifying the name of the file
as an argument to the constructor. Once the file is open, you can read from or write to it.
Inputting from a File
A file is opened for input by creating a
FileInputStream
object. Here is a commonly used
constructor:
FileInputStream(String
fileName
) throws FileNotFoundException
Here,
fileName
specifies the name of the file you want to open. If the file does not exist,
then
FileNotFoundException
is thrown.
FileNotFoundException
is a subclass of
IOEx-
ception
.
To read from a file, you can use
read( )
. The version that we will use is shown here:
int read( ) throws IOException
Each time it is called,
read( )
reads a single byte from the file and returns it as an integer
value. It returns -1 when the end of the file is encountered. It throws an
IOException
when
an error occurs. Thus, this version of
read( )
is the same as the one used to read from the
console.
When you are done with a file, you must close it by calling
close( )
. Its general form is
shown here:
void close( ) throws IOException
Closing a file releases the system resources allocated to the file, allowing them to be used
by another file. Failure to close a file can result in “memory leaks” because of unused re-
sources remaining allocated.
The following program uses
read( )
to input and display the contents of a text file, the
name of which is specified as a command-line argument. Notice how the
try
/
catch
blocks
handle I/O errors that might occur.