就我的情况而言,有效的 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
}
}
有没有办法先检查分隔符,或者允许两个分隔符?有没有比捕获异常更好的方法?