问题

我正在写一段代码:

OutputStream outputStream = new FileOutputStream(createdFile);
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(gzipOutputStream));

我是否需要关闭以下每个流或作者?

gzipOutputStream.close();
bw.close();
outputStream.close();

或者只是关闭最后一个流好吗?

bw.close();

#1 热门回答(136 赞)

假设所有流都被创建好了,是的,只需关闭bw就可以了解这些流实现;但这是一个很大的假设。

我使用try-with-resources(tutorial),以便构造抛出异常的后续流的任何问题不会使先前的流挂起,因此你不必依赖具有调用的流实现来关闭底层流:

try (
    OutputStream outputStream = new FileOutputStream(createdFile);
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
    OutputStreamWriter osw = new OutputStreamWriter(gzipOutputStream);
    BufferedWriter bw = new BufferedWriter(osw)
    ) {
    // ...
}

请注意,你不再致电closeat。

重要说明:要让资源尝试关闭它们,你必须在打开它们时将流分配给变量,不能使用嵌套。如果使用嵌套,则在构造其中一个后续流(例如,GZIPOutputStream)期间的异常将使由嵌套调用构造的任何流保持打开状态。 FromJLS §14.20.3

try-with-resources语句使用变量(称为资源)进行参数化,这些变量在执行try块之前初始化并在执行try块后以与它们初始化的相反顺序自动关闭。

注意"变量"这个词(我的重点)。

例如,不要这样做:

// DON'T DO THIS
try (BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(
        new GZIPOutputStream(
        new FileOutputStream(createdFile))))) {
    // ...
}

...因为来自GZIPOutputStream(OutputStream)构造函数的异常(表示它可能会抛出IOException,并将标头写入基础流)将离开FileOutputStream开启。由于某些资源具有可能抛出的构造函数而其他资源没有,因此将它们单独列出是一个好习惯。

我们可以用这个程序仔细检查我们对JLS部分的解释:

public class Example {

    private static class InnerMost implements AutoCloseable {
        public InnerMost() throws Exception {
            System.out.println("Constructing " + this.getClass().getName());
        }

        @Override
        public void close() throws Exception {
            System.out.println(this.getClass().getName() + " closed");
        }
    }

    private static class Middle implements AutoCloseable {
        private AutoCloseable c;

        public Middle(AutoCloseable c) {
            System.out.println("Constructing " + this.getClass().getName());
            this.c = c;
        }

        @Override
        public void close() throws Exception {
            System.out.println(this.getClass().getName() + " closed");
            c.close();
        }
    }

    private static class OuterMost implements AutoCloseable {
        private AutoCloseable c;

        public OuterMost(AutoCloseable c) throws Exception {
            System.out.println("Constructing " + this.getClass().getName());
            throw new Exception(this.getClass().getName() + " failed");
        }

        @Override
        public void close() throws Exception {
            System.out.println(this.getClass().getName() + " closed");
            c.close();
        }
    }

    public static final void main(String[] args) {
        // DON'T DO THIS
        try (OuterMost om = new OuterMost(
                new Middle(
                    new InnerMost()
                    )
                )
            ) {
            System.out.println("In try block");
        }
        catch (Exception e) {
            System.out.println("In catch block");
        }
        finally {
            System.out.println("In finally block");
        }
        System.out.println("At end of main");
    }
}

...有输出:

Constructing Example$InnerMost
Constructing Example$Middle
Constructing Example$OuterMost
In catch block
In finally block
At end of main

请注意,没有调用到close

如果我们修复main

public static final void main(String[] args) {
    try (
        InnerMost im = new InnerMost();
        Middle m = new Middle(im);
        OuterMost om = new OuterMost(m)
        ) {
        System.out.println("In try block");
    }
    catch (Exception e) {
        System.out.println("In catch block");
    }
    finally {
        System.out.println("In finally block");
    }
    System.out.println("At end of main");
}

然后我们得到相应的closecalls:

Constructing Example$InnerMost
Constructing Example$Middle
Constructing Example$OuterMost
Example$Middle closed
Example$InnerMost closed
Example$InnerMost closed
In catch block
In finally block
At end of main

(是的,两个调用4888758068是正确的;一个来自Middle,另一个来自try-with-resources。)


#2 热门回答(12 赞)

你可以关闭最外层的流,实际上你不需要保留所有包裹的流,你可以使用Java 7 try-with-resources。

try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                     new GZIPOutputStream(new FileOutputStream(createdFile)))) {
     // write to the buffered writer
}

如果你订阅YAGNI,或者你不需要它,你应该只添加你真正需要的代码。你不应该添加你可能需要的代码,但实际上并没有做任何有用的事情。

以这个例子为例,想象如果你不这样做可能会出错,影响会是什么?

try (
    OutputStream outputStream = new FileOutputStream(createdFile);
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
    OutputStreamWriter osw = new OutputStreamWriter(gzipOutputStream);
    BufferedWriter bw = new BufferedWriter(osw)
    ) {
    // ...
}

让我们从FileOutputStream开始,调用open来完成所有实际工作。

/**
 * Opens a file, with the specified name, for overwriting or appending.
 * @param name name of file to be opened
 * @param append whether the file is to be opened in append mode
 */
private native void open(String name, boolean append)
    throws FileNotFoundException;

如果找不到该文件,则没有要关闭的底层资源,因此关闭它不会有任何区别。如果文件存在,则应抛出FileNotFoundException。因此,尝试单独关闭此行的资源无法获得任何好处。

你需要关闭文件的原因是文件成功打开,但后来出错。

让我们看看下一个streamGZIPOutputStream

有代码可以抛出异常

private void writeHeader() throws IOException {
    out.write(new byte[] {
                  (byte) GZIP_MAGIC,        // Magic number (short)
                  (byte)(GZIP_MAGIC >> 8),  // Magic number (short)
                  Deflater.DEFLATED,        // Compression method (CM)
                  0,                        // Flags (FLG)
                  0,                        // Modification time MTIME (int)
                  0,                        // Modification time MTIME (int)
                  0,                        // Modification time MTIME (int)
                  0,                        // Modification time MTIME (int)
                  0,                        // Extra flags (XFLG)
                  0                         // Operating system (OS)
              });
}

这会写入文件的标题。现在,你能够打开一个文件进行写入但是不能写入8个字节是非常不寻常的,但是让我们想象这可能发生,之后我们不会关闭文件。如果文件未关闭,会发生什么?

你没有获得任何未刷新的写入,它们被丢弃,在这种情况下,没有成功写入流的字节,此时无法缓冲。但是一个未关闭的文件不会永远存在,而是FileOutputStream

protected void finalize() throws IOException {
    if (fd != null) {
        if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
            flush();
        } else {
            /* if fd is shared, the references in FileDescriptor
             * will ensure that finalizer is only called when
             * safe to do so. All references using the fd have
             * become unreachable. We can call close()
             */
            close();
        }
    }
}

如果你根本没有关闭文件,它会被关闭,但不会立即关闭(就像我说的那样,留在缓冲区中的数据会以这种方式丢失,但此时没有)

不立即关闭文件的后果是什么?在正常情况下,你可能会丢失一些数据,并且可能会耗尽文件描述符。但是如果你有一个系统,你可以创建文件,但你不能写任何东西,你有一个更大的问题。即使你失败,很难想象为什么你会反复尝试创建这个文件。

OutputStreamWriter和BufferedWriter都不会在其构造函数中抛出IOException,因此不清楚它们会导致什么问题。在BufferedWriter的情况下,你可能会得到一个OutOfMemoryError。在这种情况下,它会立即触发GC,正如我们所见,无论如何都会关闭文件。


#3 热门回答(6 赞)

如果已经实例化了所有流,那么仅关闭最外层就好了。

关于Closeable接口的文档说明了close方法:

关闭此流并释放与其关联的所有系统资源。

释放系统资源包括关闭流。

它还指出:

如果流已经关闭,则调用此方法无效。

因此,如果你事后明确地关闭它们,那么不会发生任何错误。


原文链接