Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

java - Reading CSV file using BufferedReader resulting in reading alternative lines

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first time you're reading the line without processing it in the while loop, 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...