Concept

How does try-with-resources simplify closing file input resources?

ComputerScienceOne / File Input

"We could have placed all this code within one large try-catch block with perhaps a finally block to close the Scanner once we were done to ensure that it would be closed regardless of any exceptions. However, Java 7 introduced a new construct, the try-with-resources statement. The try-with-resources statement allows us to place the initialization of a “closeable” resource, defined by the AutoCloseable interface, into the try statement. The JVM will then automatically close this resource upon the conclusion of the try-catch block. We can still provide a finally block if we wish, but this relieves us of the need to explicitly close the resource in a finally block. A full example is:\n\nFile f = new File(\"/user/apps/data.txt\");\n\n//initialize a Scanner in the try statement\n\ntry (Scanner s = new Scanner(f)) {\n\nString line;\n\nwhile(s.hasNext()) {\n\nline = s.nextLine();\n\n//process the line\n\n}\n\n} catch (Exception e) {\n\n//handle the exception here\n\n}"

Related Ideas

How does try-with-resources simplify closing file input resources? | ComputerScienceOne | Bifalgorithm | Bifalgorithm