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
resetmethod, unless it has not been used before; - Invoke the
encodemethod zero or more times, as long as additional input may be available, passingfalsefor the endOfInput argument and filling the input buffer and flushing the output buffer between invocations; - Invoke the
encodemethod one final time, passingtruefor the endOfInput argument; and then - Invoke the
flushmethod 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.