For my specific task, I need to read the data from FileChannel
to a Stream
(or Collection
) of String
\'s.
In a regular
I assume you want the channel to be closed when the returned Stream
is closed, so the simplest approach would be
public static Stream 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”.