问题描述
对于我的特定任务,我需要将数据从FileChannel
读取到String
的Stream
(或Collection
).
For my specific task, I need to read the data from FileChannel
to a Stream
(or Collection
) of String
's.
在Path
的常规NIO
中,我们可以使用便捷的方法Files.lines(...)
来返回Stream<String>
.我需要得到相同的结果,但是要从FileChannel
而不是Path
:
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) {
//...
}
有什么想法怎么做?
推荐答案
我假设您希望在返回的Stream
关闭时关闭通道,所以最简单的方法是
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); }
});
}
实际上并不需要FileChannel
作为输入,ReadableByteChannel
就足够了.
It doesn’t actually require a FileChannel
as input, a ReadableByteChannel
is sufficient.
请注意,这也属于常规NIO"; java.nio.file
有时称为"NIO.2"
Note that this also belongs to "regular NIO"; java.nio.file
is sometimes referred to as "NIO.2".
这篇关于读取从FileChannel到字符串流的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!