Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read next line with BufferedReader in Java?

I have a text file. I want to read it line by line and turn it into an 2-dimensional array. I have written something as follows:

BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line = br.readLine();

while( line != null) {                
    System.out.printf(line);  
}

This turns into an infinite loop. I want to move on to the next line after I'm done with reading and printing a line. But I don't know how to do that.

like image 616
mert dökümcü Avatar asked Dec 11 '22 00:12

mert dökümcü


2 Answers

You only read the first line. The line variable didn't change in the while loop, leading to the infinite loop.

Read the next line in the while condition, so each iteration reads a line, changing the variable.

BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line;

while( (line = br.readLine() ) != null) {
    System.out.printf(line);
}
like image 186
rgettman Avatar answered Dec 14 '22 22:12

rgettman


BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line = br.readLine();

while( line != null) {

    System.out.printf(line);

    // read the next line
    line = br.readLine();
}

... or read the line in the while condition (as rgettman pointed out):

String line;
while( (line = br.readLine()) != null) {

    System.out.printf(line);

}
like image 37
Jason Avatar answered Dec 14 '22 23:12

Jason