简体   繁体   English

如何在 Java 中使用 BufferedReader 读取下一行?

[英]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. line变量在while循环中没有变化,导致无限循环。

Read the next line in the while condition, so each iteration reads a line, changing the variable.读取while条件中的下一行,因此每次迭代读取一行,更改变量。

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): ...或阅读 while 条件中的行(如 rgettman 指出的):

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

    System.out.printf(line);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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