使用BufferedReader读取文本文件 [英] Using BufferedReader to read Text File
问题描述
我使用BufferedReader有问题
I'm having problems with using the BufferedReader
我想打印文本文件的6行:
I want to print the 6 lines of a text file:
public class Reader {
public static void main(String[]args) throws IOException{
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
while (br.readLine() != null) {
System.out.println(br.readLine());
}
in.close();
}
现在我每次调用readLine ()方法会自动前进到下一行。
Now from what I can gather every time I call the readLine() method it automatically advances to the next line.
所以我不能使用条件br.readLine()!= null,因为它已经提前一个行,我得到输出:
So I can't use the condition br.readLine() != null since it'll already advance it one line and I get the output:
Line 2
Line 4
Line 6
我使用什么条件来检查文本字段中是否还有一行。
What Condition do I use to check if there is still a new line in the text field.
提前感谢!
推荐答案
这是问题:
while (br.readLine() != null) {
System.out.println(br.readLine());
}
您有两个调用 readLine
- 第一个只有检查有一行(但读取它并将其丢弃),第二个读取下一个行。你想要:
You've got two calls to readLine
- the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
现在我们只调用 readLine() / code> 一次循环迭代,并使用我们已经读过的我们完成了的行?和打印出行部分。
Now we're only calling readLine()
once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.
这篇关于使用BufferedReader读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!