UTF-8 BOM Survives readString

Java UTF-8 decoding does not strip the BOM, so Files.readString on an Excel-style export starts with U+FEFF and header matches silently fail.

JavaFile Upload

Code

snippet
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class BomParsing {

    public static void main(String[] args) throws Exception {
        Path csv = Files.createTempFile("export-", ".csv");

        // Excel 系工具导出常带 UTF-8 BOM(EF BB BF)在文件头
        byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
        Files.write(csv, bom);
        Files.write(csv, "id,name\n1,ada\n".getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.APPEND);

        // Java 的 UTF-8 解码不剥 BOM:it survives readString,首字符是 U+FEFF
        String text = Files.readString(csv, StandardCharsets.UTF_8);
        System.out.println("first code point: 0x" + Integer.toHexString(text.charAt(0)));
        System.out.println("header match    : " + text.startsWith("id,name"));

        // 解析前剥掉 BOM,否则表头匹配静默失败
        String cleaned = text.replace("\uFEFF", "");
        System.out.println("cleaned match   : " + cleaned.startsWith("id,name"));
        Files.delete(csv);
    }
}

The three bytes that break header matching

The demo writes EF BB BF — the UTF-8 BOM — to a temp CSV, appends "id,name\n1,ada\n", and reads it back with Files.readString(csv, StandardCharsets.UTF_8). Java’s UTF-8 decoding does not strip the BOM, so the string starts with the character U+FEFF, an invisible zero-width space. Every byte of the header is intact, yet text.startsWith("id,name") returns false — the failure is silent, exactly as the title says.

What the run prints

first code point: 0xfeff
header match    : false
cleaned match   : true

Integer.toHexString(text.charAt(0)) names the intruder: 0xfeff. After text.replace("\uFEFF", "") removes it, cleaned.startsWith("id,name") turns true — same bytes, one invisible character removed. The demo then deletes the temp file with Files.delete(csv).

The line that repairs the text

String cleaned = text.replace("\uFEFF", "");

Strip the BOM before parsing — a parser fed U+FEFFid,name will not match headers, and because the character renders as nothing, the bug hides in plain sight.

Interactive Tools for This Topic

FAQ

What does UTF-8 BOM Survives readString print when run?
No setup needed: run the file and look for labeled lines like `first code point: 0x`, `header match :`, `cleaned match :` in the output.