从 CSV 文件中读取解析 error/problem

Reading from a CSV file parsing error/problem

您好,我在读取每行包含 3 列的 csv 文件时遇到问题。我似乎无法将最后一个单元格 (3) 解析为整数,即使它始终是 "parsable" 字符串: 柏林,布宜诺斯艾利斯,7402 我似乎无法得到 7402 所有编译器抛出的是:

” 在 java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) 在 java.base/java.lang.Integer.parseInt(Integer.java:658) 在 java.base/java.lang.Integer.parseInt(Integer.java:776)

这是我的代码:

Scanner scan = new Scanner("worldcities.csv");
        scan.useDelimiter("[,\n]"); // get everything before a comma or a newline
        while(scan.hasNext()) { // while this file has something then we
            edge.v1 = scan.next(); // take vertice1 ----> city 1
            edge.v2 = scan.next(); //take vertice2 ----> city 2
            edge.e = Integer.parseInt(scan.next()); // parse the third value as int(distance between city1 and city2)
            minheap.add(edge);
        }
        scan.close();

我似乎能够在调试器中获得前 2 个值。

控制台只显示“

您可以使用 nextLine() 方法遍历文件行,如本例所示:

Scanner scanner = new Scanner(new File("worldcities.csv"));
while (scanner.hasNextLine()) {
    String columns[] = scanner.nextLine().split(",");
    edge.v1 = columns[0]; // take vertice1 ----> city 1
    edge.v2 = columns[1]; //take vertice2 ----> city 2
    edge.e = Integer.parseInt(columns[2]); // parse the third value as int(distance between city1 and city2)
    minheap.add(edge);
}
scanner.close();

或使用 Files class 而不使用 Scanner:

List<String> rows = Files.readAllLines(Paths.get("worldcities.csv"));
for (String row : rows) {
    String columns[] = row.split(",");
    edge.v1 = columns[0]; // take vertice1 ----> city 1
    edge.v2 = columns[1]; //take vertice2 ----> city 2
    edge.e = Integer.parseInt(columns[2]); // parse the third value as int(distance between city1 and city2)
    minheap.add(edge);
}

您还可以使用一个特殊的库来处理 CVS 文件,例如查看 Apache Commons CSV 库。