从 CSV 文件读取解析错误/问题

Reading from a CSV file parsing error/problem

提问人:Aidan 提问时间:3/24/2020 更新时间:3/25/2020 访问量:481

问:

您好,我在读取每行包含 3 列的 csv 文件时遇到问题。我似乎无法将最后一个单元格 (3) 解析为整数,即使它始终是“可解析”字符串: 柏林,布宜诺斯艾利斯,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 个值。

控制台只显示”

java 正则表达 csv java.util.scanner 分隔符

评论

0赞 jose praveen 3/24/2020
stackoverflow.com/questions/39849984/......
0赞 Pieterjan Deconinck 3/24/2020
CSV 文件中使用哪种类型的换行符?您的代码适用于 \n (Unix),但不适用于例如 \r\n (Windows)。如果您使用的是 Windows,则可能需要更改分隔符。
0赞 Aidan 3/24/2020
我尝试使用 \r,它似乎解决了 Integer 部分的问题,但它将 \n 带到下一个单元格

答:

0赞 Ilya Lysenko 3/25/2020 #1

您可以使用以下方法循环访问文件行,如下例所示: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();

或者使用不带 :FilesScanner

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 库。