what is try with resource?

The try with resources statement is a try statement that we declares one or more resources.

  • This statement is ensures that each resource is closed at the end of the complete execution.
  • All input object is implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
  • There are no need to add finally block for closing statements of the resources.

The following example reads the line from a file. It uses an instance of FileReader and BufferedReader to read data from the file. FileReader and BufferedReader are resources that must be closed complete execution program.

				
					public class TestResource {
	public static void main(String[] args) {
		try (BufferedReader br = new BufferedReader(new FileReader("C:\\testFile.txt"))) {
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *