Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...