Java Reference
In-Depth Information
•
UTF-16LE
•
UTF-16
When constructing a
charset
, you should be prepared to handle the possible ex-
ceptions that can occur when the character set is not supported:
•
java.nio.charset.IllegalCharsetNameException
,
thrown when the
charset
name is illegal
•
java.lang.IllegalArgumentException
, thrown when the
charset
name is
null
•
java.nio.charset.UnsupportedCharsetException
,
thrown when your JVM doesn't support the targeted
charset
12-8. Converting Character Streams and
Buffers
Problem
You need to convert large blocks of Unicode character text to and from an arbitrary
byte-oriented encoding. Large blocks of text may come from streams or files.
Solution 1
Use
java.io.InputStreamReader
to decode a byte stream to Unicode charac-
ters. Use
java.io.OutputStreamWriter
to encode Unicode characters to a
byte stream.
The following code uses
InputStreamReader
to read and convert a potentially
large block of text bytes from a file in the class path. The
org.java8recipes.chapter12.recipe12_8.StreamConversion
class
provides the complete code for this example:
public String readStream() throws IOException {
InputStream is
= getClass().getResourceAsStream("resource/