Search code examples
javaexceptionnullpointerexceptionbufferedreader

Can BufferedReader be closed automatically in Java


I was getting an warning on resource leak (BufferedReader was not closed). I fixed that by putting a close statement before the Return statement and ran the program. But I got an NullPointerException. My question is can it be closed automatically (somehow) when file reading was done. This question looks similar though.


Solution

  • You can use try-with-resources Java 7 feature:

    try(BufferedReader rdr = new BufferedReader(...)) {
         ...
    }
    

    it will be closed automatically when exiting block

    http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html