gpt4 book ai didi

java - 如果我们使用 try-with-resource 是否需要关闭资源

转载 作者:行者123 更新时间:2023-12-02 08:30:32 24 4
gpt4 key购买 nike

我在代码中使用了 try-with-resource block ,想知道是否需要在方法结束时关闭资源或不需要?

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();
}
}

最佳答案

没有。

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.

如果您使用的是 java 6 或更早版本:

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.

更新:

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

正如您在代码中使用的那样。

关于java - 如果我们使用 try-with-resource 是否需要关闭资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com