在我的情况下,有效的 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
}
}
有没有办法先检查分隔符,或者允许两个分隔符?任何人都有比捕捉异常更好的主意吗?