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

Posted

技术标签:

【中文标题】如何将此 try-finally 更改为 try-with-resources?【英文标题】:How do I change this try-finally to try-with-resources? 【发布时间】:2021-03-11 17:44:51 【问题描述】:

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

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

            
        
    

【讨论】:

以上是关于如何将此 try-finally 更改为 try-with-resources?的主要内容,如果未能解决你的问题,请参考以下文章

使用没有“catch”块的“try-finally”块

第9项:尽量使用try-with-resources而不是try-finally(Prefer try-with-resources to try-finally)

Java,try-finally 没有捕获

Try-finally 阻止 ***Error

tryresources优于try-finally

Java io丑陋的try-finally块