Check out the CharsetEncoder
and CharsetDecoder
API descriptions – You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder
:
- Reset the encoder via the
reset
method, unless it has not been used before; - Invoke the
encode
method zero or more times, as long as additional input may be available, passingfalse
for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations; - Invoke the
encode
method one final time, passingtrue
for the endOfInput argument; and then - Invoke the
flush
method so that the encoder can flush any internal state to the output buffer.
By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.