用opencsv读取csv

时间:2014-11-21 11:55:09

标签: java csv opencsv

List<First> listfirst(String dir){    
        try {           
            List<First> list=new ArrayList<First>();                       
            CSVReader reader = new CSVReader(new FileReader(dir));
            String [] nextLine;
            while ((nextLine = reader.readNext()) != null) {
             // nextLine[] is an array of values from the line
            list.add(new First(nextLine[0], nextLine[1], nextLine[2],nextLine[3], nextLine[4],nextLine[5], nextLine[6], nextLine[7])); 
            }           
            return list;
        } catch (Exception e) {               
            e.printStackTrace();
            return null;
        }
    }

有1994行。但是这段代码只能打印388行。我该怎么办?

2 个答案:

答案 0 :(得分:1)

这就是我建议阅读应该是这样的:

读取文件

import au.com.bytecode.opencsv.CSVReadProc;
import java.util.Arrays;

csv.read("example.csv", new CSVReadProc() {
    public void procRow(int rowIndex, String... values) {
        System.out.println(rowIndex + ": " + Arrays.asList(values));
    }
});

答案 1 :(得分:0)

如果您希望阅读整个CSV,请阅读一次,然后重复它,

    List<String[]> allRows = reader.readAll();

      //Read CSV line by line and use the string array as you want
     for(String[] row : allRows){
        System.out.println(Arrays.toString(row));
     }
   }

并尝试使用CSVReader的构造函数,

CSVReader reader = new CSVReader(new FileReader("input.csv"), ',', '"', 0);
// 0 refers the 1st line