对于我的特定任务,我需要将数据从FileChannel
读取到String
的Stream
(或Collection
(。
在Path
的常规NIO
中,我们可以使用一种方便的方法Files.lines(...)
该方法返回一个Stream<String>
。我需要得到相同的结果,但来自FileChannel
而不是Path
:
public static Stream<String> lines(final FileChannel channel) {
//...
}
有什么想法吗?
我假设您希望在返回的Stream
关闭时关闭通道,因此最简单的方法是
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); }
});
}
它实际上不需要FileChannel
作为输入,ReadableByteChannel
就足够了。
请注意,这也属于"常规蔚来"; java.nio.file
有时被称为"NIO.2"。