Read all lines from FileChannel to Stream of strings

前端 未结 1 1554
一向
一向 2021-02-14 05:30

For my specific task, I need to read the data from FileChannel to a Stream (or Collection) of String\'s.

In a regular

相关标签:
1条回答
  • 2021-02-14 05:58

    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); }
        });
    }
    

    It doesn’t actually require a FileChannel as input, a ReadableByteChannel is sufficient.

    Note that this also belongs to “regular NIO”; java.nio.file is sometimes referred to as “NIO.2”.

    0 讨论(0)
提交回复
热议问题