对于我的具体任务,我需要阅读从FileChannel
到Stream
(或Collection
)String
的数据。
对于NIO
的常规Path
,我们可以使用方便的Files.lines(...)
方法返回Stream<String>
。我需要获得相同的结果,但需要FileChannel
而不是Path
:
public static Stream<String> lines(final FileChannel channel) {
//...
}
任何想法如何做到这一点?
答案 0 :(得分:10)
我假设您希望在返回的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
就足够了。
请注意,这也属于“常规NIO”; java.nio.file
有时是referred to as “NIO.2”。