2

I want to write a csv file in Excel format (utf-8-bom) with the apache.commons.csv and the apache.commons.io. It have only a BOMInputStream method. It is a little paradox but i can't find any howto's for writing csv files in utf-8-bom for Excel.

Is it possible with java to write files with the BOM-coding? Have anybody a idea to make this? Thanks for help!

6H057845H
  • 55
  • 7

2 Answers2

0

This issue is delt with in this question. In general BOM is allowed but neither needed nor recommended in UTF-8. So all you need is to write a file in UTF-8. For details see the link to the question that deals with this issue

Michael Gantman
  • 4,318
  • 1
  • 12
  • 31
-1

If you are adding header to CSV, simplest solution is to prefix first column header with BOM bytes:

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. Otherwise you have to make sure to write BOM before CSVPrinter writes header.