Non-blocking (NIO) reading of lines

Viewed 38822

I need to read a file line by line using java.nio, but nio doesn't have a method like readline() to read one, complete line at a time. What solutions are there?

9 Answers

1) You could convert a BufferedReader to a Stream using the lines method

List<String> list = new ArrayList<>();

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    list = br.lines().collect(Collectors.toList());    
}

2) Get a Stream directly using the Files.lines method:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream
        .filter(s -> s.endswith("/"))
        .map(String::toUpperCase)
        .forEach(System.out::println);
}

As DanielBraun points out in his answer, you could also use the readAllLines method instead of the lines method, difference being, straight from the docs:

Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.

The package summary page from Java docs gives a nice and concise overview about Streams, and this article also lists out a few other ways of reading a file by line in Java.

Related