Reading lines with BufferedReader and checking for end of file

女生的网名这么多〃 提交于 2019-11-29 03:54:40

Am... You can simply use such construction:

String line;

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

You can use the following to check for the end of file.

public bool isEOF(BufferedReader br)  
{
     boolean result;

     try 
     {
         result = br.ready();
     } 
     catch (IOException e)
     {
         System.err.println(e);
     }
     return result;
}

If you want loop through all lines use that:

while((line=br.readLine())!=null){
    System.out.println(line);
}
br.close();

In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.

String line = r.readLine();
while(line!=null){
   System.out.println(line);
   line = r.readLine();
}
Abhinav

A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class LineOperation {
    public static void main(String[] args) throws IOException {
            Files.newBufferedReader(Paths.get("C://xyz.txt")).
            lines().
            collect(Collectors.toSet()). // You can also use list or any other Collection
            forEach(System.out::println);
    }

}

You could purposely have it throw the error inside your loop. i.e.:

String s = "";
while (true) {
    try {
        s = r.readline();
    }catch(NullPointerException e) {
        r.close();
        break;
    }
    //Do stuff with line
}

what everyone else has sad should also work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!