这是代码。 大多数示例不允许我使用通过函数参数获得的响应变量。 有谁可以帮我解答这个问题吗? 或者在这种情况下使用 try-finally 比 try-with-resources 更好?
public void func(HttpServletResponse response) throws IOException {
OutputStream out = null;
InputStream in = null;
try {
out = response.getOutputStream();
ResponseEntity<Resource> url = getUrl();
Resource body = url.getBody();
in = body.getInputStream();
FileCopyUtils.copy(in, out);
} finally {
if (out != null) {
try {
out.close();
}catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
}catch (IOException e) {
}
}
}
}
最佳答案
您可以使用 try-with-resources 来做到这一点构造
public void func(HttpServletResponse response) throws IOException {
try (OutputStream out = response.getOutputStream) {
out = response.getOutputStream();
ResponseEntity<Resource> url = getUrl();
Resource body = url.getBody();
try(InputStream in = body.getInputStream()) {
FileCopyUtils.copy(in, out);
}
}
}
关于java - 如何将此 try-finally 更改为 try-with-resources?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66587767/