How do I change this try-finally to try-with-resources?

Viewed 130

This is the code. Most of the examples do not let me to use response variable which I got with the function's parameter. Is there anyone who can help me with this question? Or is it better to use try-finally than try-with-resources in this case?

    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 Answers

You can do it this way using try-with-resources construct

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

            }
        }
    }
Related