Video in progress

Strong Middle 📁 IO and NIO

Text comes out garbled in a file from an external system. How do you pin down the encoding problem?

First look at the bytes themselves (xxd, hexdump): that tells you the real encoding. Then look along the chain for where the corruption happens: reading, inside Java, the DB connection, the HTTP response. To stop silent replacement, you can use CharsetDecoder in REPORT mode.

📖 Answer

The look of the characters tells you a lot:

  • Тош: UTF-8 bytes were read as Latin-1/windows-1252;
  • Òîøêåíò: windows-1251 bytes were read as Latin-1;
  • � (U+FFFD): the decoder didn't understand a byte and silently replaced it; the original data does not come back;
  • ?: while encoding (writing), no byte was found for this character.

Looking at the bytes:

head -c 64 input.csv | xxd
# ef bb bf  — UTF-8 BOM
# d0 a2 d0 be — UTF-8 Cyrillic

By default, Java silently turns invalid bytes into �. That hides the error. A strict decoder:

CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
        .onMalformedInput(CodingErrorAction.REPORT)
        .onUnmappableCharacter(CodingErrorAction.REPORT);
try (var r = new BufferedReader(new InputStreamReader(Files.newInputStream(p), dec))) {
    // MalformedInputException if there is an invalid byte
}

Note: Files.readAllLines and Files.lines are already strict: they throw MalformedInputException. The "couldn't read the file" error often comes from this.

Other places in the chain: the encoding in the JDBC URL (utf8mb4 in MySQL), a missing charset=... in the HTTP Content-Type: text/csv; charset=..., and the UTF-8 BOM sticking to the first column name (id). Java does not strip the BOM by itself.