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 should you close files in C?ComputerScienceOne · Closing Files
- How do you write and read binary data in C?ComputerScienceOne · Closing Files
- How does PHP handle file input and output?ComputerScienceOne · Opening Files
- How do buffered and unbuffered file input/output differ?ComputerScienceOne · Buffered and Unbuffered
- What is 22?ComputerScienceOne · Opening Files