BufferedReader readLine()问题:检测文件结束和空返回行 [英] BufferedReader readLine() issue: detecting end of file and empty return lines

查看:818
本文介绍了BufferedReader readLine()问题:检测文件结束和空返回行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的程序在最后一行文本末尾找到文件结尾(EOF)时执行某些操作,而当EOF位于最后一行文本后的空行时则需要执行其他操作。不幸的是,BufferedReader似乎认为两种情况都是相同的。

I want my program to do something when it finds the end of a file (EOF) at the end of the last line of text, and something else when the EOF is at the empty line AFTER that last line of text. Unfortunately, BufferedReader seems to consider both cases equal.

例如,这是我读取文件末尾行的代码:

For example, this is my code to read the lines to the end of the file:

FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line;

while((line = br.readLine()) != null) {
    if (line.equals("")) {
        System.out.println("Found an empty line at end of file.");
    }
}

如果file.txt包含此内容,则不会打印:

If file.txt contained this, it wouldn't print:

line of text 1
another line 2//cursor

这也不会打印:

line of text 1
another line 2
//cursor

然而,这个将:

line of text 1
another line 2

//cursor

我可以用什么读者来区分前两种情况?

What reader can I use to differentiate the first two cases?

推荐答案

您必须使用读取而不是 readLine 并自己处理线端检测。 readLine 考虑 \ n \ r ,以及EOF都是行终止符,并且在返回的内容中不包含终结符,因此您无法根据返回的字符串进行区分。

You'll have to use read rather than readLine and handle end-of-line detection yourself. readLine considers \n, \r, and EOF all to be line terminators, and doesn't include the terminator in what it returns, so you can't differentiate on the basis of the returned string.

这篇关于BufferedReader readLine()问题:检测文件结束和空返回行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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