本文介绍了使用apache commons csv读取csv文件时跳过双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Reader in = new FileReader(dataFile);
Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().withIgnoreEmptyLines(true).withTrim().parse(in);

        // Reads the data in csv file until last row is encountered
        for (CSVRecord record : records) {

            String column1= record.get("column1");

csv文件中的column1值类似于"1234557".因此,当我阅读该列时,其开头是用引号引起的.Apachecommon csv中有什么方法可以跳过这些列.

Here the column1 value in csv file is something like "1234557. So whe I read the column it is fetched with the quotes at the start. Is there any way in Apache commons csv to skip those.

来自csv文件的样本数据:""0996108562",""204979956"

Sample data from csv file:"""0996108562","""204979956"

推荐答案

此MCVE无法使用commons-csv-1.4.jar进行复制(最小,完整,和可验证的示例):

Unable to reproduce using commons-csv-1.4.jar with this MCVE (Minimal, Complete, and Verifiable example):

String input = "column1,column2\r\n" +
               "1,Foo\r\n" +
               "\"2\",\"Bar\"\r\n";
CSVFormat csvFormat = CSVFormat.RFC4180.withFirstRecordAsHeader()
                                       .withIgnoreEmptyLines(true)
                                       .withTrim();
try (CSVParser records = csvFormat.parse(new StringReader(input))) {
    for (CSVRecord record : records) {
        String column1 = record.get("column1");
        String column2 = record.get("column2");
        System.out.println(column1 + ": "+ column2);
    }
}

输出:

1: Foo
2: Bar

"2""Bar"周围的引号已被删除.

The quotes around "2" and "Bar" have been removed.

这篇关于使用apache commons csv读取csv文件时跳过双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:20