对于我的特定任务,我需要从 FileChannel
中读取数据到 Stream
(或 Collection
)属于 String
的。
在常规 NIO
对于 Path
我们可以使用一个方便的方法Files.lines(...)
返回 Stream<String>
.我需要得到相同的结果,但是来自 FileChannel
而不是 Path
:
public static Stream<String> lines(final FileChannel channel) {
//...
}
有什么办法吗?
最佳答案
我假设您希望在返回的 Stream
关闭时关闭 channel ,所以最简单的方法是
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
就足够了。
注意,这也属于“regular NIO”; java.nio.file
有时是 referred to as “NIO.2” .
关于java - 从 FileChannel 读取所有行到字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544945/