java 使用 BufferedReader 读取 CSV 文件导致读取替代行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11990211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:11:27  来源:igfitidea点击:

Reading CSV file using BufferedReader resulting in reading alternative lines

javacsv

提问by prakashjv

I'm trying to read a csvfile from my java code. using the following piece of code:

我正在尝试从我的 java 代码中读取csv文件。使用以下代码:

public void readFile() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    lines = new ArrayList<String>();
    String newLine;
    while ((newLine = br.readLine()) != null) {
        newLine = br.readLine();
        System.out.println(newLine);
        lines.add(newLine);
    }
    br.close();
}

The output I get from the above piece of code is every alternative line [2nd, 4th, 6th lines] is read and returned by the readLine()method. I'm not sure why this behavior exists. Please correct me if I am missing something while reading the csv file.

我从上面这段代码得到的输出是每个替代行 [2nd, 4th, 6th lines] 被该readLine()方法读取并返回。我不确定为什么会出现这种行为。如果我在阅读 csv 文件时遗漏了什么,请纠正我。

回答by GingerHead

The first time you're reading the line without processing it in the whileloop, then you're reading it again but this time you're processing it. readLine()method reads a line and displaces the reader-pointer to the next line in the file. Hence, every time you use this method, the pointer will be incremented by one pointing to the next line.

第一次读取该行时没有在while循环中处理它,然后您再次读取它,但这次您正在处理它。readLine()方法读取一行并将读取器指针移到文件中的下一行。因此,每次使用此方法时,指针都会增加一个指向下一行。

This:

这:

 while ((newLine = br.readLine()) != null) {
        newLine = br.readLine();
        System.out.println(newLine);
        lines.add(newLine);
    }

Should be changed to this:

应该改成这样:

 while ((newLine = br.readLine()) != null) {
        System.out.println(newLine);
        lines.add(newLine);
    }

Hence reading a line and processing it, without reading another line and then processing.

因此读取一行并处理它,而不是读取另一行然后处理。

回答by Roman

You need to remove the first line in a loop body newLine = br.readLine();

您需要删除循环体中的第一行 newLine = br.readLine();