Java Reference
In-Depth Information
File I/O Using Character Streams
Although byte-oriented file handling is the most common, it is possible to use character-
based streams for this purpose. The advantage to the character streams is that they operate
directly on Unicode characters. Thus, if you want to store Unicode text, the character
streams are certainly your best option. In general, to perform character-based file I/O, you
will use the
FileReader
and
FileWriter
classes.
Using a FileWriter
FileWriter
creates a
Writer
that you can use to write to a file. Two commonly used con-
structors are shown here:
FileWriter(String
fileName
) throws IOException
FileWriter(String
fileName
, boolean
append
) throws IOException
Here,
fileName
is the full path name of a file. If
append
is
true
, then output is appended
to the end of the file. Otherwise, the file is overwritten. Either throws an
IOException
on
failure.
FileWriter
is derived from
OutputStreamWriter
and
Writer
. Thus, it has access
to the methods defined by these classes.
Here is a simple key-to-disk utility that reads lines of text entered at the keyboard and
writes them to a file called "test.txt". Text is read until the user enters the word "stop". It
uses a
FileWriter
to output to the file.