Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all lines from FileChannel to Stream of strings

For my specific task, I need to read the data from FileChannel to a Stream (or Collection) of String's.

In a regular NIO for a Path we can use a convenient method Files.lines(...) which returns a Stream<String>. I need to get a same result, but from a FileChannel instead of Path:

public static Stream<String> lines(final FileChannel channel) {
//...
}

Any ideas how to do that?

like image 761
Yuriy Yunikov Avatar asked Jun 14 '17 12:06

Yuriy Yunikov


1 Answers

I assume you want the channel to be closed when the returned Stream is closed, so the simplest approach would be

public static Stream<String> lines(FileChannel channel) {
    BufferedReader br = new BufferedReader(Channels.newReader(channel, "UTF-8"));
    return br.lines().onClose(() -> {
        try { br.close(); }
        catch (IOException ex) { throw new UncheckedIOException(ex); }
    });
}

It doesn’t actually require a FileChannel as input, a ReadableByteChannel is sufficient.

Note that this also belongs to “regular NIO”; java.nio.file is sometimes referred to as “NIO.2”.

like image 116
Holger Avatar answered Sep 19 '22 18:09

Holger