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

2022-09-01 18:42:11

我用这个: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");
        }
    }
}

我只关闭 .我是否还需要关闭 ()?PrintStreamFileOutputStreamout.close();


答案 1

不需要,您只需要关闭最外层的流。它将一直委托给包装的流。

但是,您的代码包含一个概念故障,关闭应该发生在 中,否则当代码在打开和关闭之间引发异常时,它永远不会关闭。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();
    }
}

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

或者,当您已经在Java 7上时,您还可以使用ARM(自动资源管理;也称为试用资源),这样您就不需要自己关闭任何东西:

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;
    }
}

答案 2

否,这里是 的方法的实现: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;
        }
    }

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


推荐