使用 BufferedReader 读取文本文件 [英] Using BufferedReader to read Text File

查看:43
本文介绍了使用 BufferedReader 读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 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() 一次,并使用我们读过的那一行来作为我们完成了吗?"和打印出线"部分.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆