Java |关闭资源的最安全方法

问题描述 投票:0回答:1

问题

在 Java 中关闭“i/O 资源”的最佳/最安全方法是什么?

上下文

来自 python 背景,它使用

with
创建一个 Context Manager 语句来 读写文件,它确保上下文的资源如果关闭/清理(技术上这可以是任何东西,但是内置的 io 操作例如一旦超出范围就会关闭,甚至套接字)

所以拿这个代码:

file = open('workfile', encoding="utf-8")
read_data = f.read()
file.close()

推荐的方式是使用

with
语句

with open('workfile', encoding="utf-8") as file:
    read_data = file.read()

当我们退出 with 范围(从字面上看,前一个缩进级别)时,即使发生错误,文件 也将始终关闭

我们当然可以这样做

try:
    file = open('workfile', encoding="utf-8")
    read_data = f.read()
except Exception as _: 
    pass
finally:
    file.close()

但是,大多数情况下,上下文管理器更好。一个原因是,只是有人可能会忘记写下

file.close()
,而且,只是更干净和安全。

Java 示例代码

现在在java中,推荐什么,类似为什么要处理这个?

Scanner
为例:

public class App 
{
    public static void main( String... args )
    {
        Scanner reader = new Scanner(System.in);
        try {
            System.out.print(">>> username: ");
            if (reader.hasNextLine()) {
                String username = reader.nextLine();
                System.out.format("Hello %s", username);
            }
        } catch (Exception error) {
            System.out.format("Error while reading scanner %s", error);
        } finally {
            reader.close();
        }


    }
}

如您所见,这就是我的处理方式,

这是
java
的方式吗?

python java memory-leaks io resources
1个回答
0
投票

我认为你可以使用

try(...){...}catch{}
声明
(try with resource statement)
.

例如:

try (
           Scanner reader = new Scanner(System.in);
           // other resource initalization
 ) {
            System.out.print(">>> username: ");
            if (reader.hasNextLine()) {
                String username = reader.nextLine();
                System.out.format("Hello %s", username);
            }
        } catch (Exception error) {
            System.out.format("Error while reading scanner %s", error);
        }

从JDK 1.7开始,

()
后面的
try
用于初始化一个或多个程序结束后必须关闭的资源。这种方法不需要
finally

© www.soinside.com 2019 - 2024. All rights reserved.