Search code examples
javabufferedreaderreadline

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.


Solution

  • 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);
    }