Java Reference
In-Depth Information
Table 7-5.
Comparing Classes from Byte-based Output Streams and Character-based Output Streams
Byte-based Output Stream Class
Character-based Output Stream Class
OutputStream
Writer
ByteArrayOutputStream
CharArrayWriter
StringWriter
No corresponding class
PipedOutputStream
PipedWriter
FileOutputStream
FileWriter
OutputStreamWriter
No corresponding class
FilterOutputStream
FilterWriter
BufferedOutputStream
BufferedWriter
DataOutputStream
No corresponding class
ObjectOutputStream
No corresponding class
PrintStream
PrintWriter
Some of the classes in the byte-based input/output streams do not have the corresponding character-based
classes and vice versa. For example, reading and writing primitive data and objects are always byte-based; therefore,
you do not have any classes in the reader/writer class family corresponding to the data/object input/output streams.
I have discussed how to use the byte-based input/output classes in detail in the previous sections. You will find
the classes in the reader/writer and the input/output categories similar. They are also based on the decorator pattern.
In the reader class hierarchy,
BufferedReader
, which is a concrete decorator, is directly inherited from the
Reader
class instead of the abstract decorator
FilterReader
class. In the writer class hierarchy, all concrete decorators have been
inherited from the
Writer
class instead of the
FilterWriter
. No concrete decorator inherits the
FilterWriter
class.
The two classes,
InputStreamReader
and
OutputStreamWriter
, in the reader/writer class family provide the
bridge between the byte-based and character-based streams. If you have an instance of
InputStream
and you
want to get a
Reader
from it, you can get that by using the
InputStreamReader
class. That is, you need to use the
InputStreamReader
class if you have a stream that supplies bytes and you want to read characters by getting those
bytes decoded into characters for you. For example, if you have an
InputStream
object called
iso
, and you want to get
a
Reader
object instance, you can do so as follows:
// Create a Reader object from an InputStream object using the
// platform default encoding
Reader reader = new InputStreamReader(iso);
If you know the encoding used in the byte-based stream, you can specify it while creating a
Reader
object as follows:
// Create a Reader object from an InputStream using the "US-ASCII" encoding
Reader reader = new InputStreamReader(iso, "US-ASCII");
Similarly, you can create a
Writer
object to spit out characters from a bytes-based output stream as follows,
assuming that
oso
is an
OutputStream
object:
// Create a Writer object from OutputStream using the platform default encoding
Writer writer = new OutputStreamWriter(oso);