java - 如何解析可能具有两个分隔符之一的 CSV 文件?

标签 java csv apache-commons-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
   }
}

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

最佳答案

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

关于java - 如何解析可能具有两个分隔符之一的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954105/

相关文章:

java - 如何在Android上定义圆形ImageView?

java - javax.media.jai 类(class)的公共(public)下载?

java - 如何在Spring-MVC方法中绑定(bind)抽象类的子类?

c# - 各地区的数制问题

java-8 - Apache Commons CSV 解析器 : Not able to read the values

java - 检查字符串是否包含由空格分隔的子字符串

python - csv在循环python内的行中写入替代空格

csv - 使用高级 CSV 对齐制表符分隔文件中的列

java - Apache 通用 CSV 格式化程序 : IOException: invalid char between encapsulated token and delimiter

java - 在java中使用apache commons编写CSV时包括双引号