【java初学者】 问关于流的关闭的问题?

看书看到有个地方没看明白,想问下。
代码如下:

clipboard.png
clipboard.png

图中的代码:

try (FileInputStream in = new FileInputStream("./TestDir/build.txt");
    FileOutputStream out = new FileOutputStream("./TestDir/subDir/build.txt"))

书上说,这一段,是自动资源管理的写法,不需要自己关闭流,这是什么意思呢?
我们平常写代码,最后不都是要

in.close;
out.close;

关闭流么?
这个地方为什么不用关呢?

阅读 2.6k
3 个回答

早年的java代码中大多都是这种写法:

try {
    Stream stream = // 初始化代码
} catch (Exception e) {
    // 异常处理代码
} finally {
    stream.close();
}

在java 7 引入了新的语法try-with-resource,如果你需要关闭的资源实现了AutoCloaeable接口,那么可以这么写:

// 最后一个resource不用加分号
try (Resource1; Resource2; Resource3; ,...) {

} catch (Exception e) {

}

不用在finally显式调用close()方法了

Java7 引入了 try-with-resource 语句。通过实现 AutoCloseable 接口,可以在 try catch 过程中自动关闭资源(执行 close方法)。

// Test.java
public class Test implements AutoCloseable {
    public void test() {
        System.out.println("execute function test.");
    }
    @Override
    public void close() throws Exception {
        System.out.println("close.");
    }
}
// main
try (Test test = new Test();){
    test.test();
} catch (Exception e) {
    System.out.println("catch");
}
// console
execute function test.
close.

一楼答的正确,这里附上AutoCloseable的注释:

/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * @apiNote
 * <p>It is possible, and in fact common, for a base class to
 * implement AutoCloseable even though not all of its subclasses or
 * instances will hold releasable resources.  For code that must operate
 * in complete generality, or when it is known that the {@code AutoCloseable}
 * instance requires resource release, it is recommended to use {@code
 * try}-with-resources constructions. However, when using facilities such as
 * {@link java.util.stream.Stream} that support both I/O-based and
 * non-I/O-based forms, {@code try}-with-resources blocks are in
 * general unnecessary when using non-I/O-based forms.
 *
 * @author Josh Bloch
 * @since 1.7
 */

FileInputStreamFileOutputStream实现了java.lang.AutoCloseable接口。由于他们俩被定义在try-with-resource 语句中,因此不管try代码块是正常完成或是出现异常,这个FileInputStreamFileOutputStream的实例都将被关闭。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题