选择第二列(FileReader)

Selecting second column (FileReader)

我正在循环 csv。我有两个问题:

1) 我正在 select 按名称排列第二列,例如

if(tab[1].equals("Col2")

我不想输入列名。我只想 select 第二列。

2) 如何跳过第一行 (header)

这是循环 csv 的代码示例:

String csvFile = "C:\test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";

try{
    br = new BufferedReader(new FileReader(csvFile));

    while ((line = br.readLine()) != null) {
        String[] tab=line.split(cvsSplitBy);      

        int tmp;
        if(tab[1].equals("Col2")){                

            tmp = Integer.parseInt(tab[2]);

                for(int i=0;i<tmp;i++){  
                   // TO DO
                }
        }
    }
}

为此最好使用 CSVReader,它提供了很多 API 来处理您的 csv 文件。这是一个完整的工作代码,当然,没有异常处理。

String csvFile = "C:\test.csv";
CSVReader reader;
String[] nextRow;
char cvsSplitBy = ';';

try {

    //Last argument will determine how many lines to skip. 1 means skip header
    reader = new CSVReader(new FileReader(csvFile), cvsSplitBy, CSVParser.DEFAULT_QUOTE_CHARACTER, 1);

    while ((nextRow = reader.readNext()) != null) {

        if(nextRow.length > 2){
            //nextRow[1] will always give second column value
            int tmp = Integer.parseInt(nextRow[1]);
            for (int i = 0; i < tmp; i++) {
                // TO DO
            }
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

这是一个使用 Apache Commons CSV 及其 CSVParser 的示例。

第一行被认为是 header 并被跳过 (withFirstRecordAsHeader()) ,每个记录的 "columns" 可以通过它们的索引访问 (get(int) ) .The indexes are based .

只需根据您的需要调整字符集和CSVFormat

CSVParser parser = null;

try {

    parser = CSVParser.parse(new File(csvFile), Charset.forName("UTF-8"),
            CSVFormat.RFC4180.withFirstRecordAsHeader());

    List<CSVRecord> records = parser.getRecords();

    for (CSVRecord record : records) {

        int tmp = Integer.parseInt(record.get(1));

        for (int i = 0; i < tmp; i++) {
            // TO DO
        }

    }

} catch (IOException e) {

    e.printStackTrace();

} finally {
    try {
        parser.close();
    } catch (IOException e) {

    }

}

对于 univocity-parsers 这变得小菜一碟:

CsvParserSettings parserSettings = new CsvParserSettings(); //many options here, check the tutorial.
parserSettings.setHeaderExtractionEnabled(true); //header is extracted and not part of the result
parserSettings.selectIndexes(1); //select 2nd column (indexes are 0-based)
CsvParser parser = new CsvParser(parserSettings);
List<String[]> allRows = parser.parseAll(csvFile);

请注意,即使某些行是空的或只有一列,这也会起作用,而此处发布的所有其他解决方案都将失败,除非您自己处理此类情况。

不仅这涉及更少的代码(和复杂性),解析器也比 Commons CSV 快约 4 倍,比 OpenCSV 快约 3 倍。

免责声明:我是这个库的作者,它是开源且免费的(Apache v2.0 许可)