如何解析可能具有两个分隔符之一的 CSV 文件?
2022-09-04 04:08:31
在我的情况下,有效的CSV是由逗号或分号分隔的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
}
}
有没有办法先检查分隔符,或者允许两个分隔符?有没有人有比抓住一个例外更好的想法?