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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With