Java Try With Explained with Code Samples
The Java try with statement allows you to declare some resources with the try statement. Java automatically closes these resources once the try statement ends. This makes the code clean. Java introduced the try-with statement as part of Java 7. Without Try/With Consider the following code that does not use try-with: public static void saveFile(String fileName, String content) { try { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName)); bufferedWriter.write(content); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } This code uses BufferedWriter to write to a file. Once the code finishes writing the content to the file, it closes the BufferedWriter. Using try/With You can re-write the above code using a try-with statement as follows: public static void saveFile2(String fileName, String content) { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName))){ bufferedWriter.write(content); ...