使用BufferedReader读取行并检查文件结尾 [英] Reading lines with BufferedReader and checking for end of file

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

问题描述

如果我的代码中有这样的内容:

If I have something like this in my code:

String line = r.readLine();  //Where r is a bufferedReader

如果下一行是结束,我怎么能避免崩溃文件? (即null)

How can I avoid a crash if the next line is the end of the file? (i.e. null)

我需要阅读下一行,因为我可能需要处理某些内容,但如果没有代码只是崩溃。

I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.

如果有什么东西那么一切都没问题,但我不能保证那里会有东西。

If there is something there then all is OK, but I can't be guaranteed that there will be something there.

所以如果我这样做:(伪代码):

So if I do something like: (pseudo code):

if (r.readLine is null)
//End code

else {check line again and excecute code depending on what the next line is}

我遇到的问题是,当我检查该行反对null时,它已经移动到下一行,那么我该如何再次检查呢?

The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?

我还没有想出办法 - 任何建议都会有很大的帮助。

I've not worked out a way to do this - any suggestions would be a great help.

推荐答案

Am ...你可以简单地使用这样的结构:

Am... You can simply use such construction:

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}

这篇关于使用BufferedReader读取行并检查文件结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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