gpt4 book ai didi

java - 从 FileChannel 读取所有行到字符串流

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:03 53 4
gpt4 key购买 nike

对于我的特定任务,我需要从 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/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com