The Coordinator
The Coordinator

Reputation: 13137

How to prevent a try-with-resources from closing a BufferedReader from lines() (Stream<String>)?

This is what I am doing to prevent a BufferedReader from being closed when lines() finishes in a try-with-resources:

This is a general utility and it operates on a whole lot of Readers, not just Files ..

public static List<String> getLines(Reader reader, boolean trim, boolean closeReader) throws IOException {
        Objects.requireNonNull(reader);
        BufferedReader br = new BufferedReader(reader) {

            @Override
            public void close() throws IOException {
                if (closeReader) {
                    super.close();
                }
            }

        };

        try (Stream<String> lines = br.lines()) {
            return lines.map(it -> trim ? it.trim() : it)
                    .collect(Collectors.toList());
        }
    }

Is there any better way of controlling so that the closing of Stream<String> does not also close the Bufferedreader?

As per the comments below to try a normal try, it would look like this:

public static List<String> getLines(Reader reader, boolean trim, boolean closeReader) throws IOException {
    Objects.requireNonNull(reader);
    BufferedReader br = new BufferedReader(reader);

    try {
        return br.lines()
                .map(it -> trim ? it.trim() : it)
                .collect(Collectors.toList());
    } finally {
        if (closeReader) {
            br.close();
        }
    }
}

That seems better :)

Upvotes: 1

Views: 933

Answers (2)

Aleksandr Dubinsky
Aleksandr Dubinsky

Reputation: 23515

You don't need to close a Stream, unless you need to close an underlying resource.

Most Streams (such as those pointing to in-memory collections) don't need closing at all.

MOREOVER, the Stream returned by BufferedReader.lines() will not close the BufferedReader if closed! (in b119) Use Files.lines() instead.

Upvotes: 1

ruakh
ruakh

Reputation: 183504

I don't think that what you describe is possible. Your try-with-resources is just closing the lines, not br. It is lines itself that is closing br; and there's no way to close lines without closing br.

What's more, I don't understand why you would want to avoid closing br. You are reading all the way to the end of the reader (by performing collect); what's the point of keeping it open after that?

Upvotes: 2

Related Questions