我是否必须关闭由PrintStream包装的FileOutputStream?

hs2*_*s2d 18 java stream

我使用的是FileOutputStreamPrintStream这样的:

class PrintStreamDemo {  
    public static void main(String args[]) { 
        FileOutputStream out; 
        PrintStream ps; // declare a print stream object
        try {
            // Create a new file output stream
            out = new FileOutputStream("myfile.txt");

            // Connect print stream to the output stream
            ps = new PrintStream(out);

            ps.println ("This data is written to a file:");
            System.err.println ("Write successfully");
            ps.close();
        }
        catch (Exception e) {
            System.err.println ("Error in writing to file");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我只关闭了PrintStream.我还需要关闭FileOutputStream(out.close();)吗?

Bal*_*usC 25

不,你只需要关闭最外面的流.它将一直委托给包装的流.

但是,您的代码包含一个概念性失败,关闭应该发生finally,否则当代码在打开和关闭之间抛出异常时它永远不会关闭.

例如

public static void main(String args[]) throws IOException { 
    PrintStream ps = null;

    try {
        ps = new PrintStream(new FileOutputStream("myfile.txt"));
        ps.println("This data is written to a file:");
        System.out.println("Write successfully");
    } catch (IOException e) {
        System.err.println("Error in writing to file");
        throw e;
    } finally {
        if (ps != null) ps.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

(注意我更改了代码以抛出异常,以便您了解问题的原因,异常即包含有关问题原因的详细信息)

或者,当您已经使用Java 7时,您还可以使用ARM(自动资源管理;也称为try-with-resources),这样您就不需要自己关闭任何内容:

public static void main(String args[]) throws IOException { 
    try (PrintStream ps = new PrintStream(new FileOutputStream("myfile.txt"))) {
        ps.println("This data is written to a file:");
        System.out.println("Write successfully");
    } catch (IOException e) {
        System.err.println("Error in writing to file");
        throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 6

不,根据 javadoc,close 方法将为您关闭底层流。


Ser*_*yan 6

不,这里是实现PrintStreamclose()方法:

public void close() {
    synchronized (this) {
        if (! closing) {
        closing = true;
        try {
            textOut.close();
            out.close();
        }
        catch (IOException x) {
            trouble = true;
        }
        textOut = null;
        charOut = null;
        out = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以看到out.close();哪个关闭输出流.


Mec*_*kov 5

不,你不需要。PrintStream.close 方法自动关闭下划线输出流。

检查 API。

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#close%28%29