如何将此 try-finally 更改为 try-with-resources?

时间:2021-03-11 17:44:51

标签: java try-catch backend try-with-resources try-with

这是代码。 大多数示例不允许我使用我通过函数参数获得的响应变量。 有没有人可以帮我解决这个问题? 还是在这种情况下使用 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) {
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:3)

您可以使用 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);

            }
        }
    }