Try-With-Resources Example
This program demonstrates try-with-resources for automatic resource management.
Problem Statement
Write a Java program that reads a file using try-with-resources.
Source Code
| 1 | import java.io.*; |
| 2 | public class TryWithResourcesExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Try-With-Resources Example"); |
| 5 | try(BufferedReader br=new BufferedReader(new FileReader("nonexistent.txt"))) { |
| 6 | System.out.println("Eduinq File Content: "+br.readLine()); |
| 7 | } catch(IOException e) { |
| 8 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 9 | } |
| 10 | } |
| 11 | } |
Program Output
Eduinq Try-With-Resources Example Eduinq Exception: nonexistent.txt (No such file or directory)
Explanation
Try-with-resources automatically closes resources after use. - Eliminates need for explicit finally block cleanup. - Improves reliability and reduces resource leaks. - In enterprise systems, ensures safe handling of files, streams, and connections. Conclusion: Shows try-with-resources for automatic resource management.