将csv文件读取到arraylist对象

时间:2015-03-11 14:43:58

标签: java csv arraylist

问题在于CVSParser类。我需要阅读.CSV文件,然后将其传递给ArrayList<Club>

Example.csv
团队,W,d,L,GF,GA
阿森纳,24,7,7,68,41
阿斯顿维拉,10,8,20,39,61
...

分类课程

public Club(String team, int w, int l, int d, int GF, int GA) {
        ...
    }

CSVParser类

public static ArrayList<Club> CSVParser(String file) throws IOException{

        ArrayList<Club> Lists = new ArrayList<>();
        try{
        Scanner scanner = new Scanner(new FileReader(file));
        scanner.nextLine();

        while(scanner.hasNextLine()){
            String line = scanner.nextLine();
            //System.out.println(line);

            /*will get ArrayIndexOutOfBoundsException: 0 error */
            String[] splits = line.split(",");
            Lists.add(new Club(splits[0], Integer.parseInt(splits[1]),Integer.parseInt(splits[2]), 
                    Integer.parseInt(splits[3]), Integer.parseInt(splits[4]), Integer.parseInt(splits[5])));

        }scanner.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }

        System.out.println(Lists);
        return Lists;

1 个答案:

答案 0 :(得分:1)

首先,这是使用扫描仪的正确方法

Scanner s = new Scanner(input).useDelimiter(",");
int w = s.nextInt());

否则,只需使用BufferedReader

接下来,在csvfile中有一个或多个空行,你应该在拆分之前检查行长度,如:

if (line.trim().length() > 0) {
    String[] splits = line.split(",");
}