0

在使用具有以下 maven 依赖项的 Apache CSV 时。我得到了意想不到的结果。

  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.2</version>
</dependency>

简单的代码无法按预期为我工作。谁能告诉这里有什么问题?

System.out.println(CSVFormat.DEFAULT.format("-10","10"));

实际输出:"-10",10

预期输出:-10,10

System.out.println(CSVFormat.DEFAULT.format("10","-10"));

实际输出:10,-10

预期输出:10,-10

System.out.println(CSVFormat.DEFAULT.format(".10","-10"));

实际输出:".10",-10

预期输出:.10,-10

System.out.println(CSVFormat.DEFAULT.format("+10","-10"));

实际输出:"+10",-10

预期输出:+10,-10

4

1 回答 1

1

您上面列出的实际结果是合法的 CSV 格式(即使使用引号也可以解析),但我可以看到它看起来像是一个意外的输出。

以下是中的源代码CSVPrinter.java

// TODO where did this rule come from?
if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) {
    quote = true;
}

如果行中的第一项不以字母数字字符开头,此代码将引用它。

如果您浏览该类的代码历史记录,您会发现这种行为从存储库开始(2011 年 11 月 9 日)就一直存在。

我没有注意到问题跟踪器上有任何相关的错误,所以如果你认为应该更改默认行为,你应该打开一个问题。或者,您可以考虑使用QuoteMode using CSVFormat.withQuoteMode().

于 2016-04-16T15:26:51.303 回答