简体   繁体   English

爪哇| Apache Commons CSV | 如何使用 utf-8-bom 编写 csv 文件?

[英]Java | Apache Commons CSV | How can i write a csv file with utf-8-bom?

I want to write a csv file in Excel format (utf-8-bom) with the apache.commons.csv and the apache.commons.io.我想用 apache.commons.csv 和 apache.commons.io 以 Excel 格式(utf-8-bom)编写一个 csv 文件。 It have only a BOMInputStream method.它只有一个 BOMInputStream 方法。 It is a little paradox but i can't find any howto's for writing csv files in utf-8-bom for Excel.这有点自相矛盾,但我找不到在 utf-8-bom 中为 Excel 编写 csv 文件的任何方法。

Is it possible with java to write files with the BOM-coding? java是否可以使用BOM编码编写文件? Have anybody a idea to make this?有没有人有做这个的想法? Thanks for help!感谢您的帮助!

This issue is delt with in this question .这个问题在这个问题中很明显 In general BOM is allowed but neither needed nor recommended in UTF-8.通常,在 UTF-8 中允许使用 BOM,但既不需要也不推荐使用 BOM。 So all you need is to write a file in UTF-8.所以你所需要的只是用 UTF-8 写一个文件。 For details see the link to the question that deals with this issue有关详细信息,请参阅处理此问题的问题的链接

If you are adding header to CSV, simplest solution is to prefix first column header with BOM bytes:如果要向 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 ...
}

This way you can use one 'try with resources' without caring when CSVPrinter prints header.通过这种方式,您可以在 CSVPrinter 打印标题时使用一个“尝试使用资源”而无需关心。 Otherwise you have to make sure to write BOM before CSVPrinter writes header.否则,您必须确保在 CSVPrinter 写入标题之前写入 BOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM