Apache CSV 引号字符不适用于多列

问题描述

我读了一个非常简单的 CSV 文件,如下所示:

String csv = "'ID','fruit'\n'1','apple'\n'2','banana'\n'3','cherry'";

try (InputStream resourceInputStream = new ByteArrayInputStream(csv.getBytes());
    InputStreamReader inputStreamReader = new InputStreamReader(resourceInputStream);) {

  CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',').withHeader()
          .withSkipHeaderRecord(false).withRecordSeparator("\n").withTrim().withQuote('\'');
  CSVParser parser = format.parse(inputStreamReader);
  Iterator<CSVRecord> iterator = parser.iterator();

  while (iterator.hasNext()) {
    CSVRecord next = iterator.next();
    System.out.println(next.toMap());
  }
}

这会将以下内容打印到控制台:

{ID=1,'fruit'='apple'}
{ID=2,'fruit'='banana'}
{ID=3,'fruit'='cherry'}

虽然我当然希望:

{ID=1,fruit=apple}
{ID=2,fruit=banana}
{ID=3,fruit=cherry}

而且它也不是纯粹的装饰,如果引号内有分隔符,则将其用作不存在引号。 (所以使用“che,rry”会将“rry”放在第三列中。)

它也不适用于 " 而不是 '。它不适用于默认引号(也应该是 ")。它不适用于 withQuoteMode()。它不适用于以前的 Apache CSV 版本(当前是 1.8,我测试了 1.7 和 1.6)。

有没有人知道我需要做什么才能使引号在第二列和以下列中起作用?

没关系:它正在与 withIgnoreSurroundingSpaces()

解决方法

标题中的空格和 CSV 文本中的值似乎混淆了 commons-csv,使用以下字符串输出看起来不同:

输入:

String csv = "'ID','fruit'\n" +
    "'1','apple'\n" +
    "'2','banana'\n" +
    "'3','cherry'";

输出:

{ID=1,fruit=apple}
{ID=2,fruit=banana}
{ID=3,fruit=cherry}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...