Java是否会自动关闭在Try Block主体中声明的自动固有S?

发布于 2025-02-13 21:12:35 字数 373 浏览 0 评论 0原文

我有以下代码,

try (Scanner scanner = new Scanner(new File(path))){
    while(scanner.hasNextLine()){
        Scanner delimit = new Scanner(scanner.nextLine()).useDelimiter("-");
        ...
    }
}
...

我了解括号中的扫描仪将自动关闭,但是我从未明确关闭delimit,并且对资源泄漏没有任何警告。那么,Java是否会自动关闭任何自动固有 -s在Try Block主体中声明的声明,还是这是一个错误,我应该收到资源泄漏警告?

I have the following code

try (Scanner scanner = new Scanner(new File(path))){
    while(scanner.hasNextLine()){
        Scanner delimit = new Scanner(scanner.nextLine()).useDelimiter("-");
        ...
    }
}
...

I understand that the scanner in parentheses will be closed automatically, however I never explicitly close delimit and I get no warning about a resource leak. So does Java automatically close any AutoClosable-s declared in try block body or is this a bug and I should be getting a resource leak warning?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不打扰别人 2025-02-20 21:12:35

不,Java不会关闭体内声明的每个资源。 Java会自动关闭“尝试声明的资源”,以便您可以将代码更改为如下,然后Java将自动关闭它 -

try (Scanner scanner = new Scanner(new File(path))){
while(scanner.hasNextLine()){
    try (Scanner delimit = new Scanner(scanner.nextLine()).useDelimiter("-")){
    ...
    }
}

}

No, java wont close every resource declared in body. Java automatically will close the resources declared with try so you can change your code to like below, then java will close it automatically -

try (Scanner scanner = new Scanner(new File(path))){
while(scanner.hasNextLine()){
    try (Scanner delimit = new Scanner(scanner.nextLine()).useDelimiter("-")){
    ...
    }
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文