如何解析可能具有两个分隔符之一的 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
   }
}

有没有办法先检查分隔符,或者允许两个分隔符?有没有人有比抓住一个例外更好的想法?


答案 1

我们在 uniVocity 解析器中构建了对此的支持:

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许可证)


答案 2

我遇到了同样的问题,我以这种方式解决了这个问题:

    BufferedReader in = Files.newBufferedReader(Paths.get(fileName));
    in.mark(1024);
    String line = in.readLine();
    CSVFormat fileFormat;
    
    if(line.indexOf(';') != -1)
        fileFormat = CSVFormat.EXCEL.withDelimiter(';');
    else
        fileFormat = CSVFormat.EXCEL;
    
    in.reset();

之后,您可以使用 解析它。CSVParser