Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

java - Does closing a Stream close the BufferedReader source?

From the docs:

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

When I create a Stream<String> using the lines() method on a BufferedReader as seen below, does closing the Stream also close the BufferedReader?

try (Stream<String> lines = new BufferedReader(new InputStreamReader(process.getInputStream())).lines()) {
  // Do stuff
}

// Is the BufferedReader, InputStreamReader and InputStream closed?

Some really quick tests I've tried say no (the in field of the BufferedReader is not null), but then I'm confused by the following sentence, since this example is I/O as well, right?

Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing.

If not, do I need to close both instances, or will closing the BufferedReader suffice?


Ideally, I'd like to return a Stream<String> from some method, without having the client worry about the readers. At the moment, I've created a Stream decorator which also closes the reader, but it's easier if that isn't necessary.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to defer closing of the reader to the delivered Stream you need to invoke Stream.onClose():

static Stream<String> toStream(BufferedReader br){
    return br.lines().onClose(asUncheckedAutoCloseable(br));
}


static Runnable asUncheckedAutoCloseable(AutoCloseable ac) {
    return () -> {
        try {
            ac.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...