【问题标题】:Read csv file to arraylist object读取 csv 文件到 arraylist 对象
【发布时间】:2015-03-11 14:43:58
【问题描述】:

问题在于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;

【问题讨论】:

  • 您的帖子以“问题出在...”开头,但您的帖子甚至没有开始描述问题。
  • 你为什么将FileReader 传递给你的Scanner 而不是File

标签: java csv arraylist


【解决方案1】:

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

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

否则,只需使用 BufferedReader

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多