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
   }
}

最初に区切り文字を確認する方法、またはおそらく 2 つの区切り文字を許可する方法はありますか? 例外をキャッチするよりも良いアイデアはありますか?

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

この問題の私の解決策の下:

    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 に答える