Java Reference
In-Depth Information
The following statement creates a
Charset
object for the ISO-8859-1 character set:
Charset isoset = Charset.forName(“ISO-8859-1”);
After you have a character set object, you can use it to create encoders and decoders. Call
the object's
newDecoder()
method to create a
CharsetDecoder
and the
newEncoder()
method to create an
CharsetEncoder
.
To transform a byte buffer into a character buffer, call the decoder's
decode(
ByteBuffer
)
method, which returns a
CharBuffer
containing the bytes transformed into characters.
To transform a character buffer into a byte buffer, call the encoder's
encode(
CharBuffer
)
method. A
ByteBuffer
is returned containing the byte values of the characters.
The following statements convert a byte buffer called
netBuffer
into a character buffer
using the ISO-8859-1 character set:
Charset set = Charset.forName(“ISO-8859-1”);
CharsetDecoder decoder = set.newDecoder();
netBuffer.position(0);
CharBuffer netText = decoder.decode(netBuffer);
17
Before the decoder is used to create the character buffer, the call
to
position(0)
resets the current position of the
netBuffer
to the
start. When working with buffers for the first time, it's easy to over-
look this, resulting in a buffer with much less data than you
expected.
CAUTION
Channels
A common use for a buffer is to associate it with an input or output stream. You can fill a
buffer with data from an input stream or write a buffer to an output stream.
To do this, you must use a
channel
, an object that connects a buffer to the stream.
Channels are part of the
java.nio.channels
package.
Channels can be associated with a stream by calling the
getChannel()
method available
in some of the stream classes in the
java.io
package.
The
FileInputStream
and
FileOutputStream
classes have
getChannel()
methods that
return a
FileChannel
object. This file channel can be used to read, write, and modify the
data in the file.