← 中文资源

简体中文版本

UTF-8 BOM 不被 readString 剥除

Java 的 UTF-8 解码不剥 BOM:Excel 导出的 CSV 经 readString 后首字符是 U+FEFF(零宽不可见),表头匹配静默失败;解析前要先剥掉。

阅读英文原文

实现说明

除了类 BomParsing,文件里再无其他定义。

使用要点

  • 演示输出是带标签的(first code point: 0x、header match :、cleaned match :),每个操作都会留下自己的一行标注。

常见问题

运行「UTF-8 BOM 不被 readString 剥除」会打印什么?

整个文件跑完,输出行以 first code point: 0x、header match :、cleaned match : 这类前缀开头。

核心语句

String text = Files.readString(csv, StandardCharsets.UTF_8);
byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
Path csv = Files.createTempFile("export-", ".csv");

代码示例

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);
    }
}