在我的例子中,有效的 CSV 是由逗号或分号分隔的。我对其他库开放,但它需要是 Java。通读 Apache CSVParser API,我唯一能想到的就是这样做,这看起来效率低下且丑陋。
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
CSVFormat csvFormat = CSVFormat.EXCEL.withHeader().withDelimiter(';');
CSVParser parser = csvFormat.parse( reader );
// now read the records
}
catch (IOException eee)
{
try
{
// try the other valid delimeter
csvFormat = CSVFormat.EXCEL.withHeader().withDelimiter(',');
parser = csvFormat.parse( reader );
// now read the records
}
catch (IOException eee)
{
// then its really not a valid CSV file
}
}
有没有办法先检查分隔符,或者允许两个分隔符?有谁有比捕获异常更好的主意吗?
最佳答案
我们在 uniVocity-parsers 中建立了对此的支持:
public static void main(String... args) {
CsvParserSettings settings = new CsvParserSettings();
settings.setDelimiterDetectionEnabled(true);
CsvParser parser = new CsvParser(settings);
List<String[]> rows = parser.parseAll(file);
}
解析器还有许多我相信您会发现有用的功能。试一试。
免责声明:我是这个库的作者,它是开源且免费的(apache 2.0 许可)
关于java - 如何解析可能具有两个分隔符之一的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954105/