Java Reference
In-Depth Information
org.java8recipes.chapter12.recipe12_8.BufferConversion
class
encodes and decodes character sets from buffers:
public ByteBuffer encodeBuffer(String charsetName,
CharBuffer charBuffer)
throws CharacterCodingException {
Charset charset = Charset.forName(charsetName);
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer targetBuffer = encoder.encode(charBuffer);
return targetBuffer;
}
public CharBuffer decodeBuffer(String charsetName,
ByteBuffer srcBuffer)
throws CharacterCodingException {
Charset charset = Charset.forName(charsetName);
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(srcBuffer);
return charBuffer;
}
How It Works
The
java.io
and
java.nio.charset
packages contain several classes that can
help you perform encoding conversions on large text streams or buffers. Streams are
convenient abstractions that can assist you in converting text using a variety of sources
and targets. A stream can represent incoming or outgoing text in an HTTP connection
or even a file.
If you use an
InputStream
to represent the underlying source text, you will
wrap that stream in an
InputStreamReader
to perform conversions from a byte
stream. The reader instance performs the conversion from bytes to Unicode characters.
Using an
OutputStream
instance to represent the target text, wrap the stream in
an
OutputStreamWriter
. A writer will convert your Unicode text to a byte-orien-
ted encoding in the target stream.
To effectively use either an
OutputStreamWriter
or an
In-
putStreamReader
, you must know the character encoding of your target or source
text. When you use an
OutputStreamWriter
, the source text is always Unicode,