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
method, unless it has not been used before;encode
method zero or more times, as long as additional input may be available, passing false
for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;encode
method one final time, passing true
for the endOfInput argument; and thenflush
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.