java | Apache 共享 CSV |如何使用 utf-8-bom 编写 csv 文件?

标签 java maven csv byte-order-mark

我想用 apache.commons.csv 和 apache.commons.io 编写一个 Excel 格式 (utf-8-bom) 的 csv 文件。它只有一个 BOMInputStream 方法。 这是一个有点悖论,但我找不到任何如何在 Excel 中以 utf-8-bom 格式编写 csv 文件的方法。

用java可以写BOM编码的文件吗? 有人有想法做这个吗?感谢帮助!

最佳答案

如果要向 CSV 添加标题,最简单的解决方案是在第一列标题前添加 BOM 字节前缀:

public static final String UTF8_BOM = new String(new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF},StandardCharsets.UTF_8);
//...
String[] header = new String[2];
header[0] = UTF8_BOM + "column1";
header[1] = "column2";
final CSVFormat csvFormat = CSVFormat.EXCEL.withDelimiter(';').withHeader(header);
try(FileWriter fileWriter = new FileWriter(file);
        CSVPrinter csvPrinter = new CSVPrinter(fileWriter, csvFormat);){
    //write CSV data ...
}

这样,您就可以在 CSVPrinter 打印标题时使用一次“尝试资源”,而无需关心。否则,您必须确保在 CSVPrinter 写入 header 之前写入 BOM。

关于 java | Apache 共享 CSV |如何使用 utf-8-bom 编写 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964320/

相关文章:

python - 将 JSON 数据加载到 CSV 时,CSV Excel 文件格式不正确

java - 使用 aws athena 解析 CSV

Java 线程 : Specify function to Call in Thread's run function

java - 设置单击的表格单元格的背景颜色

java - 如何在 java 中随机播放 FilteredList?

java - 尝试设置旧版 Java Spring 启动应用程序时出现导入 com.fasterxml.jackson 无法解析错误

php - mysql查询后源代码中出现换行符

java - 使用 MINGW 构建 JNI DLL

multithreading - TestNG 并行测试失败

java - 如何部署具有其他artifactId的程序集?