14

在我的情况下,有效的 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
   }
}

有没有办法先检查分隔符,或者允许两个分隔符?任何人都有比捕捉异常更好的主意吗?

4

3 回答 3

8

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

于 2015-08-12T01:40:36.070 回答
0

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

    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.

于 2021-02-07T00:04:50.333 回答
0

下面我解决这个问题:

    private static final Character[] DELIMITERS = {';', ','};
    private static final char NO_DELIMITER = '\0'; //empty char

    private char detectDelimiter() throws IOException {
        try (
            final var reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        ) {
            String line = reader.readLine();

            return Arrays.stream(DELIMITERS)
                .filter(s -> line.contains(s.toString()))
                .findFirst()
                .orElse(NO_DELIMITER);
        }
    }

示例用法:

private CSVParser openCsv() throws IOException {

        final var csvFormat = CSVFormat.DEFAULT
            .withFirstRecordAsHeader()
            .withDelimiter(detectDelimiter())
            .withTrim();

        return new CSVParser(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8), csvFormat);
    }
于 2021-04-22T13:49:18.810 回答