【问题标题】:FileReader skipping every other line from CSV comma delimitted fileFileReader 从 CSV 逗号分隔文件中每隔一行跳过
【发布时间】:2021-05-03 13:56:39
【问题描述】:

为什么这段代码会跳过只有 3 列的 CSV 工作表中的每一行?

public void loadFile(String fileName) {
    try (BufferedReader csvReader = new BufferedReader(new FileReader("C:\\src\\" + fileName + "", StandardCharsets.ISO_8859_1))) {

        while (csvReader.readLine() != null) {

            String[] data = csvReader.readLine().split(",", 3);
            String sku = data[0];
            String title = data[1];
            double price = Double.parseDouble(data[2]);
            Product newProduct = new Product(sku, title, price);
            newProduct.setProducts(newProduct);
        }

    } catch (IOException e) {
        System.out.println("Could not load file: " + e.getMessage());
    }
}

【问题讨论】:

  • 每次迭代调用readLine 两次。
  • 我怀疑这是下面 iota 提出的观点,但你是 100% 正确的。 readline 作为 while 循环参数被调用一次,并在执行时再次调用。很好发现。

标签: java arrays csv filereader


【解决方案1】:

每次调用readLine,它都会读取一行并移至下一行。您需要存储读取的行。

String line;
while ((line = csvReader.readLine()) != null) {
    String[] data = line.split(",", 3);
    // ...
}

【讨论】:

  • 使用您的建议解决了。我错误地认为 while (csvReader.readLine() != null) 参数不会被执行,而只能用作限定符。但是两个地方的readLine 都强制跳过一行。
猜你喜欢
  • 1970-01-01
  • 2012-11-09
  • 2014-03-18
  • 2016-09-11
  • 2021-05-30
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
相关资源
最近更新 更多