【问题标题】:Apache CSV Quote Character Does Not Work For Multiple ColumnsApache CSV 引号字符不适用于多列
【发布时间】:2021-01-28 10:49:46
【问题描述】:

我读了一个非常简单的 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()

【问题讨论】:

    标签: java csv apache-commons apache-commons-csv


    【解决方案1】:

    CSV 文本中 header 和 value 中的空格似乎混淆了 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}
    

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 2018-10-19
      • 2021-11-07
      • 2015-12-20
      • 1970-01-01
      • 2020-05-10
      • 2014-02-08
      • 2021-05-10
      相关资源
      最近更新 更多