Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a need to close resource if we use try-with-resource

I am using try-with-resource block in my code, wondering is there a need to close the resource at the end of the method or not needed?

try (S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
  BufferedReader br = new BufferedReader(new InputStreamReader(object.getObjectContent()));
  BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))){
  String line;

  while((line=br.readLine())!=null){
    bw.write(line);
    bw.newLine();
    bw.flush();
  }
}
like image 769
Maana Avatar asked Dec 13 '22 13:12

Maana


1 Answers

No.

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

And if you are using a java 6 or older:

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

Update:

You may declare one or more resources in a try-with-resources statement.

as you have used in your code.

like image 111
ZhaoGang Avatar answered Feb 16 '23 00:02

ZhaoGang