我是 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
方法如果您想从头开始创建 CSVFormat,请使用此方法。除定界符外的所有字段都将初始化为 null/false。
如果要为每条记录添加新行分隔符,请添加withRecordSeparator
CSVFormat.newFormat(delimiter.charAt(0)).withHeader(header)).
withRecordSeparator(System.getProperty("line.separator"));
返回一个新的 CSVFormat,格式的记录分隔符设置为指定的字符。
注意:此设置仅在打印时使用,不影响解析。解析目前仅适用于带有 ' ', ' ' 和 ” “
我有同样的问题改变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();
}
更新https://stackoverflow.com/a/55606621/373498
的主要答案由于
withRecordSeparator
已弃用,您应该使用
.setRecordSeparator(System.getProperty("line.separator"))
定义换行符。
例子:
final CSVFormat csvFormat = CSVFormat.Builder
.create()
.setHeader(csvHeaders)
.setDelimiter(";")
.setQuoteMode(QuoteMode.ALL)
.setRecordSeparator("\n") // unix line feed
.setAutoFlush(true)
.setEscape('"')
.build();
final StringWriter stringWriter = new StringWriter();
try (CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat)) {
: