本文介绍了读取从FileChannel到字符串流的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的特定任务,我需要将数据从FileChannel读取到StringStream(或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到字符串流的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:43