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

问题描述

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

            }
        }
    }