Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading CSV file using BufferedReader resulting in reading alternative lines

Tags:

java

csv

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.

like image 701
prakashjv Avatar asked Nov 24 '25 10:11

prakashjv


2 Answers

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.

like image 178
GingerHead Avatar answered Nov 25 '25 22:11

GingerHead


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

like image 20
Roman Avatar answered Nov 25 '25 22:11

Roman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!