The try-with-resource statement previously required a new variable to be declared for each resource in the statement when a final variable was used. Here is the syntax for the try-with-resource statement prior to Java 9 (in Java 7 or 8):
try ( // open resources ) { // use resources } catch (// error) { // handle exceptions } // automatically close resources
Here is a code snippet using the preceding syntax:
try ( Scanner xmlScanner = new Scanner(new File(xmlFile)); { while (xmlScanner.hasNext()) { // read the xml document and perform needed operations } xmlScanner.close(); } catch (FileNotFoundException fnfe) { System.out.println("Your XML file was not found."); }
Now, with Java 9, the try-with-resource ...