我希望我的程序在最后一行文本的末尾找到文件结尾 (EOF) 时执行某些操作,并且当 EOF 位于最后一行文本之后的空行时执行其他操作。不幸的是,BufferedReader 似乎认为这两种情况是平等的。
例如,这是我读取文件末尾行的代码:
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
如果 file.txt 包含此内容,则不会打印:
line of text 1
another line 2//cursor
Run Code Online (Sandbox Code Playgroud)
这也不会打印:
line of text 1
another line 2
//cursor
Run Code Online (Sandbox Code Playgroud)
但是,这将:
line of text 1
another line 2
//cursor
Run Code Online (Sandbox Code Playgroud)
我可以使用什么阅读器来区分前两种情况?
您可以使用BufferedReader.read(char[] cbuf, int off, int len)方法。当到达文件末尾时,返回 value -1,您可以检查最后读取的缓冲区是否以行分隔符结束。
诚然,代码会更复杂,因为它必须管理来自读取char[]缓冲区的行的构造。
| 归档时间: |
|
| 查看次数: |
25258 次 |
| 最近记录: |