首页 > 解决方案 > 为 csvReader 跳过了循环

问题描述

所以,我有这种情况:我有两个 .csv 文件,我需要为它们读取和保存数据。

问题在这里:

while ((nextPM = csvReader2.readNext()) != null) {
    System.out.println(nextPM[0]);
    while ((nextRecord = csvReader.readNext()) != null) {
        System.out.println(nextRecord[0] + "asd");
        if(nextRecord[0].equals(nextPM[0])) {
            System.out.println(nextRecord[0] + " " + nextRecord[1] + " " + nextPM[2]);
        }
    }
}

第一次完美运行,但是当第一个 while 循环再次开始时,第二个 while 就被跳过了。有什么解决办法吗?当然nextPM并且nextRecordString[](在我向您展示的代码之外初始化)

标签: javacsv

解决方案


当外部循环的第一次迭代完成内部循环时,cvsReader将达到 EOF,因此任何进一步的调用csvReader.readNext()都将返回 null。

一种解决方案是不嵌套循环,而是首先将其中一个文件读取到数组或其他集合中,然后在读取第二个数组时对该数组进行处理。


推荐阅读