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

标签 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) {
                    }
                }
            }
        }

最佳答案

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

相关文章:

java - 转账方法在银行程序中不起作用

java - 查找被注释处理覆盖的方法

javascript - 这是在 javascript/node js 中编写处理错误处理 then-catch 或 try-catch 的最佳实践

java - 使用 try catch finally block 时组织 java 代码

android - Urban Airship 可以在 Android 后端的 C2DM 上运行吗?

node.js - NodeJS vs Golang for REST API 并用它实现后端

android - 移动应用程序的后端服务器

java - jetty : store request-specific information

c# - 如何在不使用 try-catch 的情况下捕获和记录 Using 语句中的异常?

java - 来自外部存储的 Uri 上的 MediaPlayer 为 null