使用BufferedReader读取行并检查文件结尾

Zip*_*ppy 11 java file-io readline bufferedreader

如果我的代码中有这样的东西:

String line = r.readLine();  //Where r is a bufferedReader
Run Code Online (Sandbox Code Playgroud)

如果下一行是文件的结尾,我该如何避免崩溃?(即null)

我需要阅读下一行,因为可能有一些我需要处理的东西,但如果没有代码只是崩溃.

如果有什么东西那么一切都没问题,但我无法保证那里会有东西.

所以,如果我做了类似的事情:(伪代码):

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

else {check line again and excecute code depending on what the next line is}
Run Code Online (Sandbox Code Playgroud)

我遇到类似这样的问题是,当我检查该行反对null时,它已经移动到下一行,所以我该如何再次检查它?

我没有找到办法做到这一点 - 任何建议都会有很大的帮助.

And*_*niy 30

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

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}
Run Code Online (Sandbox Code Playgroud)

  • 你先回答,我会删除我的:) (5认同)

Lug*_*aru 7

如果您想遍历所有行,请使用:

while((line=br.readLine())!=null){
    System.out.println(line);
}
br.close();
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用以下命令检查文件的结尾。

public bool isEOF(BufferedReader br)  
{
     boolean result;

     try 
     {
         result = br.ready();
     } 
     catch (IOException e)
     {
         System.err.println(e);
     }
     return result;
}
Run Code Online (Sandbox Code Playgroud)