10

我在 Netbeans 7.1.2 中有以下代码:

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename));
bos.write(newRawData);
bos.close();

一个警告表明我“转换为 try-with-resources”。当我选择这样做时,我的代码变为:

try (BufferedOutputStream bufferedFos = new BufferedOutputStream(new FileOutputStream(filename))) {
        bufferedFos.write(newRawData);
    }

这看起来类似于 C# 中 using(...) 的语法...它们的工作方式相同吗?使用第二种格式有什么缺点吗?我担心没有bos.close();,但是这种格式根本没有必要吗?

4

2 回答 2

14

这是 Java 7 中引入的一种新语法,它负责关闭您在声明try(...)语句时指定的任何资源。更多信息可以在这里找到。
所以不,你不必做 a bos.close(),它是由 Java 执行的。你可以坐下来放松一下。
唯一的缺点是您的代码仅适用于 Java 7+。

于 2012-07-11T20:09:34.933 回答
5

笔记

Java 7 中引入了“try with resources”语句来替代该try...finally语句。基本上,它所做的只是让您不必添加:

finally {
  if(resource != null) resource.close();
}

到你的try陈述结束。如果您使用它,您的代码将仅适用于 Java 7 及更高版本。

回答

try是 Java 中称为try...catch. 您收到的警告的完整解决方案是:

try(BufferedOutputStream bufferedFos = new BufferedOutputStream(new FileOutputStream(filename))) {
  bufferedFos.write(newRawData);
} catch(FileNotFoundException e) {
  e.printStackTrace();
}

A "try with resources" block uses the same structure as the try...catch block, but automatically closes any resources that are created inside the block once it has been executed. That's why you don't see a bufferedFos.close(); statement in the code.

于 2012-07-11T20:16:08.923 回答