简体   繁体   中英

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM