apache-commons-csv println 方法不在输出中打印换行符

apache-commons-csv println method doesn't print newline in output

我是 apache-commons-csv 1.6 的新手

我有一个基本要求,即在新行中打印每条记录的 csv 文件。我正在尝试使用 CSVPrinter 的 println 方法。由于某些奇怪的原因,输出文件没有任何换行符。所有内容都打印在一行中。

我试过在 Notepad++ 中打开输出并显示不可打印的字符。记录之间没有字符。任何帮助将不胜感激。谢谢

CSVPrinter csvPrinter = null;

if(delimiter != null && delimiter.length() > 0) {
    csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.newFormat(delimiter.charAt(0)).withHeader(header));
}else {
    csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.DEFAULT.withHeader(header));
}

for(Map<String,String> record : inputList) {
    List<String> valueList = new ArrayList<String>();
    for(String key : record.keySet()) {
        valueList.add(record.get(key));
    }
    System.out.println(valueList);
    csvPrinter.printRecord(valueList);
    csvPrinter.println();
}
csvPrinter.close();

预期结果:

id|type|value|key

4|excel|0|excel.sheet.no

5|excel|dd/MM/yyyy|excel.date.format

6|excel|0|excel.baserate.rownum

实际结果: id|type|value|key4|excel|0|excel.sheet.no5|excel|dd/MM/yyyy|excel.date.format6|excel|0| excel.baserate.rownum

如果不想覆盖 all 定界符,请不要使用 newFormat 方法

Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized with null/false.

如果要为每条记录添加新行分隔符,请添加 withRecordSeparator

CSVFormat.newFormat(delimiter.charAt(0)).withHeader(header)).
 withRecordSeparator(System.getProperty("line.separator"));

Returns a new CSVFormat with the record separator of the format set to the specified character.

Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and "\r\n"

我有同样的问题改变 withRecordSeparator 没有帮助。对于变通解决方案,我直接打印新行,如:

private static final char DELIMITER_CHAR = ',';

        try (CSVParser parser = CSVFormat.newFormat(DELIMITER_CHAR).withTrailingDelimiter(false)
                .withRecordSeparator('\n').parse(new InputStreamReader(new ByteArrayInputStream(bytes)));
             CSVPrinter printer = CSVFormat.newFormat(DELIMITER_CHAR).print(destinationFile, Charset.defaultCharset())) {
            for (CSVRecord record : parser) {
                try {
                    printer.printRecord(record);
                   // printer.println(); // TODO not working
                   printer.print('\n'); // work around solution 
                } catch (Exception e) {
                    throw new RuntimeException("Error at line " + parser.getCurrentLineNumber(), e);
                }
            }
            printer.flush();
        }