Java Reference
In-Depth Information
Note
OutputStreamWriter
depends on the abstract
java.nio.charset.Charset
and
java.nio.charset.CharsetEncoder
classes to perform character encoding.
(I discuss these classes in Appendix C.)
Thefollowingexampleusesthesecondconstructortocreateabridgetoanunderlying
file output stream so that Polish text can be written to an ISO/IEC 8859-2-encoded file.
FileOutputStream fos = new FileOutputStream("polish.txt");
OutputStreamWriter
osw
=
new
OutputStreamWriter(fos,
"8859_2");
char ch = '\u0323'; // Accented N.
osw.write(ch);
The concrete
InputStreamReader
class (a
Reader
subclass) is a bridge
betweenanincomingstreamofbytesandanoutgoingsequenceofcharacters.Charac-
ters readfromthis reader aredecoded frombytes according tothedefault orspecified
character encoding.
Each call to an
InputStreamReader read()
method may cause one or more
bytestobereadfromtheunderlyinginputstream.Toenabletheefficientconversionof
bytestocharacters,morebytesmaybereadaheadfromtheunderlyingstreamthanare
necessary to satisfy the current read operation.
InputStreamReader
declares four constructors, including the following:
•
InputStreamReader(InputStream in)
createsabridgebetweenun-
derlyinginputstream
in
andanoutgoingsequenceofcharacters(returnedfrom
InputStreamReader
via its
read()
methods). The default character en-
coding is used to decode bytes into characters.
•
InputStreamReader(InputStream in, String charsetName)
createsabridgebetweenunderlyinginputstream
in
andanoutgoingsequence
of characters (returned from
InputStreamReader
via its
read()
meth-
ods).
charsetName
identifies the character encoding used to decode bytes
into characters. This constructor throws
UnsupportedEncodingExcep-
tion
when the named character encoding isn't supported.
Note
InputStreamReader
depends on the abstract
Charset
and
java.nio.charset.CharsetDecoder
classes to perform character decoding.
(I discuss
CharsetDecoder
in Appendix C.)