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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28999757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:10:26  来源:igfitidea点击:

How do I read next line with BufferedReader in Java?

javabufferedreaderreadline

提问by Cevat Mert D?kümcü

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.

这变成了一个无限循环。完成阅读和打印一行后,我想转到下一行。但我不知道该怎么做。

采纳答案by rgettman

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

您只阅读了第一行。该line变量并没有在改变while循环,导致无限循环。

Read the next line in the whilecondition, 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);
}

回答by Jason

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

}