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?
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”.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With