Video in progress
When reading UTF-8 data in blocks, sometimes `�` appears instead of letters. What is the cause, and how do you fix it?
A UTF-8 character takes 1 to 4 bytes. If you do new String(chunk, UTF_8) on each block separately, half a character is left at the block boundary and the decoder replaces it with U+FFFD. You need a decoder that keeps state.
📖 Answer
For example, the ʻ (U+02BB) in the Uzbek oʻ is CA BB in UTF-8: two bytes. If a 4096-byte block ends with CA, both the end of the first block and the start of the second become invalid sequences.
// wrong
while ((n = in.read(buf)) > 0) {
sb.append(new String(buf, 0, n, StandardCharsets.UTF_8));
}
The simplest fix is not decoding the bytes yourself. InputStreamReader has a stateful CharsetDecoder inside that holds a partial character until the next read:
try (Reader r = new InputStreamReader(in, StandardCharsets.UTF_8)) {
char[] cbuf = new char[4096];
int n;
while ((n = r.read(cbuf)) > 0) sb.append(cbuf, 0, n);
}
If you work with NIO (for example a ByteBuffer comes in from a socket), use CharsetDecoder.decode(in, out, false). It leaves the partial bytes in the ByteBuffer; then you compact() and add the new data after them. At the end you call decode(..., true) and flush().
One more point: by default the decoder silently replaces broken bytes. If the incoming file really must be UTF-8, set newDecoder().onMalformedInput(CodingErrorAction.REPORT): it is better to raise an error than to silently corrupt a Windows-1251 file as UTF-8.
Sign up to mark studied questions and save your progress.