您可以通过univocity-parsers 阅读您的 CSV。
我们仍在开发 2.0 版,它引入了格式自动检测,但您已经可以获取快照版本并使用它来处理此问题。
简单示例:
public static void main(String... args) {
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.detectFormatAutomatically();
List<String[]> rows = new CsvParser(parserSettings).parseAll(new StringReader("Amount,Tax,Total\n1.99,10.0,2.189\n5,20.0,6"));
for (Object[] row : rows) {
System.out.println(Arrays.toString(row));
}
System.out.println("####");
rows = new CsvParser(parserSettings).parseAll(new StringReader("Amount;Tax;Total\n1,99;10,0;2,189\n5;20,0;6"));
for (Object[] row : rows) {
System.out.println(Arrays.toString(row));
}
}
输出:
[Amount, Tax, Total]
[1.99, 10.0, 2.189]
[5, 20.0, 6]
####
[Amount, Tax, Total]
[1,99, 10,0, 2,189]
[5, 20,0, 6]
您可以从here获取最新的快照版本。
或者,如果您使用 maven,请将其添加到您的 pom.xml:
<repositories>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
并将版本设置为 2.0.0-SNAPSHOT:
<dependency>
<groupId>com.univocity</groupId>
<artifactId>univocity-parsers</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
如果您发现任何问题,只需打开一个新问题in the project's github page
编辑:另一个示例演示如何使用多个格式化程序将输入行转换为 BigDecimal:
public static void main(String... args) {
// ObjectRowListProcessor converts the parsed values and stores the result in a list.
ObjectRowListProcessor rowProcessor = new ObjectRowListProcessor();
FormattedBigDecimalConversion conversion = new FormattedBigDecimalConversion();
conversion.addFormat("0.00", "decimalSeparator=.");
conversion.addFormat("0,00", "decimalSeparator=,");
// Here we convert fields at columns 0, 1 and 2 to BigDecimal, using two possible input formats
rowProcessor.convertIndexes(conversion).set(0, 1, 2);
// Create a settings object to configure the CSV parser
CsvParserSettings parserSettings = new CsvParserSettings();
//I'll separate the values using | to make it easier for you to identify the values in the input
parserSettings.getFormat().setDelimiter('|');
// We want to use the RowProcessor configured above to parse our data
parserSettings.setRowProcessor(rowProcessor);
// Create the parser
CsvParser parser = new CsvParser(parserSettings);
// Parse everything. All rows are sent to the rowProcessor configured above
parser.parse(new StringReader("1.99|10.0|2.189\n1,99|10,0|2,189"));
// Let's get the parsed rows
List<Object[]> rows = rowProcessor.getRows();
for (Object[] row : rows) {
System.out.println(Arrays.toString(row));
}
}
这是输出:2 个包含 BigDecimal 对象的数组,以及正确的值:
[1.99, 10.0, 2.189]
[1.99, 10.0, 2.189]