读取从文件通道到字符串流的所有行



对于我的特定任务,我需要将数据从FileChannel读取到StringStream(或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"。

最新更新