Should I always close BufferedReader?Does collect operation on Stream close the stream and underlying...

Removing whitespace between consecutive numbers

Is there a verb that means to inject with poison?

Should I always close BufferedReader?

Could an Apollo mission be possible if Moon would be Earth like?

Why did the villain in the first Men in Black movie care about Earth's Cockroaches?

What is a good reason for every spaceship to carry a weapon on board?

Why does magnet wire need to be insulated?

Why avoid shared user accounts?

Strange "DuckDuckGo dork" takes me to random website

How do you voice extended chords?

Why don't key signatures indicate the tonic?

Bash script to truncate subject line of incoming email

What makes papers publishable in top-tier journals?

Why do all the books in Game of Thrones library have their covers facing the back of the shelf?

Does Skippy chunky peanut butter contain trans fat?

Why maximum length of IP, TCP, UDP packet is not suit?

Cat is tipping over bed-side lamps during the night

How do I prevent a homebrew Grappling Hook feature from trivializing Tomb of Annihilation?

The probability of reaching the absorbing states from a particular transient state?

Can you tell from a blurry photo if focus was too close or too far?

Citing paid articles from illegal web sharing

How to deal with possible delayed baggage?

How can I play a serial killer in a party of good PCs?

Prioritising polygons in QGIS



Should I always close BufferedReader?


Does collect operation on Stream close the stream and underlying resources?Does a finally block always get executed in Java?What is a serialVersionUID and why should I use it?Efficiency of Java “Double Brace Initialization”?BufferedReader not stating 'ready' when it shouldConvert InputStream to BufferedReaderIs it necessary to close an InputStreamReader in a BufferedReaderBufferedReader - Does it take in the entire document?BufferedReader Doesn't Read All Of My Text FileReading a JSON file twice with BufferedReaderBufferedReader Deadlock: How to properly shutdown a BufferedReader













6















Here is a line reading a file into a List:



List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());


Is this correct or should I assign the BufferedReader to a variable to be able to close it later?










share|improve this question

























  • @MS90 - based on what? The documentation does not specify that the resource is closed.

    – RealSkeptic
    2 hours ago











  • @MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

    – RealSkeptic
    2 hours ago











  • This seems to imply close is not called by collect.

    – TiiJ7
    2 hours ago











  • @rkosegi Yes it reads everything in memory and closes it before looping.

    – MS90
    2 hours ago











  • @rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

    – rzwitserloot
    2 hours ago
















6















Here is a line reading a file into a List:



List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());


Is this correct or should I assign the BufferedReader to a variable to be able to close it later?










share|improve this question

























  • @MS90 - based on what? The documentation does not specify that the resource is closed.

    – RealSkeptic
    2 hours ago











  • @MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

    – RealSkeptic
    2 hours ago











  • This seems to imply close is not called by collect.

    – TiiJ7
    2 hours ago











  • @rkosegi Yes it reads everything in memory and closes it before looping.

    – MS90
    2 hours ago











  • @rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

    – rzwitserloot
    2 hours ago














6












6








6








Here is a line reading a file into a List:



List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());


Is this correct or should I assign the BufferedReader to a variable to be able to close it later?










share|improve this question
















Here is a line reading a file into a List:



List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());


Is this correct or should I assign the BufferedReader to a variable to be able to close it later?







java bufferedreader






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 hours ago









Mad Physicist

37.9k1674106




37.9k1674106










asked 3 hours ago









EkaterinaEkaterina

12718




12718













  • @MS90 - based on what? The documentation does not specify that the resource is closed.

    – RealSkeptic
    2 hours ago











  • @MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

    – RealSkeptic
    2 hours ago











  • This seems to imply close is not called by collect.

    – TiiJ7
    2 hours ago











  • @rkosegi Yes it reads everything in memory and closes it before looping.

    – MS90
    2 hours ago











  • @rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

    – rzwitserloot
    2 hours ago



















  • @MS90 - based on what? The documentation does not specify that the resource is closed.

    – RealSkeptic
    2 hours ago











  • @MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

    – RealSkeptic
    2 hours ago











  • This seems to imply close is not called by collect.

    – TiiJ7
    2 hours ago











  • @rkosegi Yes it reads everything in memory and closes it before looping.

    – MS90
    2 hours ago











  • @rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

    – rzwitserloot
    2 hours ago

















@MS90 - based on what? The documentation does not specify that the resource is closed.

– RealSkeptic
2 hours ago





@MS90 - based on what? The documentation does not specify that the resource is closed.

– RealSkeptic
2 hours ago













@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

– RealSkeptic
2 hours ago





@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.

– RealSkeptic
2 hours ago













This seems to imply close is not called by collect.

– TiiJ7
2 hours ago





This seems to imply close is not called by collect.

– TiiJ7
2 hours ago













@rkosegi Yes it reads everything in memory and closes it before looping.

– MS90
2 hours ago





@rkosegi Yes it reads everything in memory and closes it before looping.

– MS90
2 hours ago













@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

– rzwitserloot
2 hours ago





@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)

– rzwitserloot
2 hours ago












4 Answers
4






active

oldest

votes


















4














Well, in your concrete example, the stream opened by



classLoader.getResourceAsStream(fileName)



is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.



Please also have a look into try-with-resources, this could potentially make things easier for you here.






share|improve this answer































    4














    You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.



    An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:



    List<String> lines;
    try(BufferedReader reader = new BufferedReader(
    new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
    lines = reader.lines().collect(Collectors.toList());
    }





    share|improve this answer































      1














      Wrong answer - Streams must be closed too.



      One should alway close, which can be done with try-with-resources.



      --However here a Stream<String> is run to its final collect, hence everything is closed.--



      List<String> lines =
      new BufferedReader(
      new InputStreamReader(classLoader.getResourceAsStream(fileName),
      StandardCharsets.UTF_8))
      .lines()
      .collect(Collectors.toList());


      Or:



      try {
      URL url = classLoader.getResource(fileName);
      Path path = Paths.get(url.toURI());
      List<String> lines = Files.readAllLines(path); // Default UTF-8.
      Files.lines(path).forEach(System.out::println);
      } catch (URISyntaxException e) {
      ...
      }


      A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.






      share|improve this answer


























      • Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

        – MS90
        2 hours ago








      • 2





        Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

        – Florian Albrecht
        2 hours ago













      • Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

        – rzwitserloot
        2 hours ago






      • 1





        @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

        – Joop Eggen
        2 hours ago











      • To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

        – Joop Eggen
        2 hours ago



















      0














      I stand corrected





      From documentation:
      Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.



      Generally, only streams whose source is an IO channel, for example a BufferedReader.lines 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.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54888904%2fshould-i-always-close-bufferedreader%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        4














        Well, in your concrete example, the stream opened by



        classLoader.getResourceAsStream(fileName)



        is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.



        Please also have a look into try-with-resources, this could potentially make things easier for you here.






        share|improve this answer




























          4














          Well, in your concrete example, the stream opened by



          classLoader.getResourceAsStream(fileName)



          is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.



          Please also have a look into try-with-resources, this could potentially make things easier for you here.






          share|improve this answer


























            4












            4








            4







            Well, in your concrete example, the stream opened by



            classLoader.getResourceAsStream(fileName)



            is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.



            Please also have a look into try-with-resources, this could potentially make things easier for you here.






            share|improve this answer













            Well, in your concrete example, the stream opened by



            classLoader.getResourceAsStream(fileName)



            is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.



            Please also have a look into try-with-resources, this could potentially make things easier for you here.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 2 hours ago









            Florian AlbrechtFlorian Albrecht

            1,6051418




            1,6051418

























                4














                You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.



                An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:



                List<String> lines;
                try(BufferedReader reader = new BufferedReader(
                new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
                lines = reader.lines().collect(Collectors.toList());
                }





                share|improve this answer




























                  4














                  You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.



                  An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:



                  List<String> lines;
                  try(BufferedReader reader = new BufferedReader(
                  new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
                  lines = reader.lines().collect(Collectors.toList());
                  }





                  share|improve this answer


























                    4












                    4








                    4







                    You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.



                    An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:



                    List<String> lines;
                    try(BufferedReader reader = new BufferedReader(
                    new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
                    lines = reader.lines().collect(Collectors.toList());
                    }





                    share|improve this answer













                    You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.



                    An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:



                    List<String> lines;
                    try(BufferedReader reader = new BufferedReader(
                    new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
                    lines = reader.lines().collect(Collectors.toList());
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 2 hours ago









                    Mad PhysicistMad Physicist

                    37.9k1674106




                    37.9k1674106























                        1














                        Wrong answer - Streams must be closed too.



                        One should alway close, which can be done with try-with-resources.



                        --However here a Stream<String> is run to its final collect, hence everything is closed.--



                        List<String> lines =
                        new BufferedReader(
                        new InputStreamReader(classLoader.getResourceAsStream(fileName),
                        StandardCharsets.UTF_8))
                        .lines()
                        .collect(Collectors.toList());


                        Or:



                        try {
                        URL url = classLoader.getResource(fileName);
                        Path path = Paths.get(url.toURI());
                        List<String> lines = Files.readAllLines(path); // Default UTF-8.
                        Files.lines(path).forEach(System.out::println);
                        } catch (URISyntaxException e) {
                        ...
                        }


                        A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.






                        share|improve this answer


























                        • Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                          – MS90
                          2 hours ago








                        • 2





                          Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                          – Florian Albrecht
                          2 hours ago













                        • Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                          – rzwitserloot
                          2 hours ago






                        • 1





                          @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                          – Joop Eggen
                          2 hours ago











                        • To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                          – Joop Eggen
                          2 hours ago
















                        1














                        Wrong answer - Streams must be closed too.



                        One should alway close, which can be done with try-with-resources.



                        --However here a Stream<String> is run to its final collect, hence everything is closed.--



                        List<String> lines =
                        new BufferedReader(
                        new InputStreamReader(classLoader.getResourceAsStream(fileName),
                        StandardCharsets.UTF_8))
                        .lines()
                        .collect(Collectors.toList());


                        Or:



                        try {
                        URL url = classLoader.getResource(fileName);
                        Path path = Paths.get(url.toURI());
                        List<String> lines = Files.readAllLines(path); // Default UTF-8.
                        Files.lines(path).forEach(System.out::println);
                        } catch (URISyntaxException e) {
                        ...
                        }


                        A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.






                        share|improve this answer


























                        • Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                          – MS90
                          2 hours ago








                        • 2





                          Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                          – Florian Albrecht
                          2 hours ago













                        • Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                          – rzwitserloot
                          2 hours ago






                        • 1





                          @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                          – Joop Eggen
                          2 hours ago











                        • To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                          – Joop Eggen
                          2 hours ago














                        1












                        1








                        1







                        Wrong answer - Streams must be closed too.



                        One should alway close, which can be done with try-with-resources.



                        --However here a Stream<String> is run to its final collect, hence everything is closed.--



                        List<String> lines =
                        new BufferedReader(
                        new InputStreamReader(classLoader.getResourceAsStream(fileName),
                        StandardCharsets.UTF_8))
                        .lines()
                        .collect(Collectors.toList());


                        Or:



                        try {
                        URL url = classLoader.getResource(fileName);
                        Path path = Paths.get(url.toURI());
                        List<String> lines = Files.readAllLines(path); // Default UTF-8.
                        Files.lines(path).forEach(System.out::println);
                        } catch (URISyntaxException e) {
                        ...
                        }


                        A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.






                        share|improve this answer















                        Wrong answer - Streams must be closed too.



                        One should alway close, which can be done with try-with-resources.



                        --However here a Stream<String> is run to its final collect, hence everything is closed.--



                        List<String> lines =
                        new BufferedReader(
                        new InputStreamReader(classLoader.getResourceAsStream(fileName),
                        StandardCharsets.UTF_8))
                        .lines()
                        .collect(Collectors.toList());


                        Or:



                        try {
                        URL url = classLoader.getResource(fileName);
                        Path path = Paths.get(url.toURI());
                        List<String> lines = Files.readAllLines(path); // Default UTF-8.
                        Files.lines(path).forEach(System.out::println);
                        } catch (URISyntaxException e) {
                        ...
                        }


                        A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 2 hours ago

























                        answered 2 hours ago









                        Joop EggenJoop Eggen

                        77.6k755103




                        77.6k755103













                        • Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                          – MS90
                          2 hours ago








                        • 2





                          Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                          – Florian Albrecht
                          2 hours ago













                        • Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                          – rzwitserloot
                          2 hours ago






                        • 1





                          @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                          – Joop Eggen
                          2 hours ago











                        • To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                          – Joop Eggen
                          2 hours ago



















                        • Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                          – MS90
                          2 hours ago








                        • 2





                          Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                          – Florian Albrecht
                          2 hours ago













                        • Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                          – rzwitserloot
                          2 hours ago






                        • 1





                          @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                          – Joop Eggen
                          2 hours ago











                        • To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                          – Joop Eggen
                          2 hours ago

















                        Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                        – MS90
                        2 hours ago







                        Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)

                        – MS90
                        2 hours ago






                        2




                        2





                        Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                        – Florian Albrecht
                        2 hours ago







                        Could you please post a link which shows that collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".

                        – Florian Albrecht
                        2 hours ago















                        Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                        – rzwitserloot
                        2 hours ago





                        Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.

                        – rzwitserloot
                        2 hours ago




                        1




                        1





                        @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                        – Joop Eggen
                        2 hours ago





                        @FlorianAlbrecht point taken. Notice that Files.lines closes the stream on exception and by adding an .onClose callback for closing.

                        – Joop Eggen
                        2 hours ago













                        To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                        – Joop Eggen
                        2 hours ago





                        To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?

                        – Joop Eggen
                        2 hours ago











                        0














                        I stand corrected





                        From documentation:
                        Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.



                        Generally, only streams whose source is an IO channel, for example a BufferedReader.lines 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.






                        share|improve this answer




























                          0














                          I stand corrected





                          From documentation:
                          Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.



                          Generally, only streams whose source is an IO channel, for example a BufferedReader.lines 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.






                          share|improve this answer


























                            0












                            0








                            0







                            I stand corrected





                            From documentation:
                            Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.



                            Generally, only streams whose source is an IO channel, for example a BufferedReader.lines 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.






                            share|improve this answer













                            I stand corrected





                            From documentation:
                            Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.



                            Generally, only streams whose source is an IO channel, for example a BufferedReader.lines 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.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 1 hour ago









                            MS90MS90

                            45710




                            45710






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54888904%2fshould-i-always-close-bufferedreader%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                IEEEtran - How to include ORCID in TeX/PDF with PdfLatexIs there a standard way to include ORCID in TeX /...

                                Cicindela nigrior Przypisy | Menu nawigacyjneCicindela varians unicolorManual for the Identification of the...

                                Glossaries-extra: Adding glossaries package to “Clas­sicTh­e­sis” template by Dr. André Miede v. 4.6 ...