我是否必须关闭由 PrintStream 包装的 FileOutputStream? [英] Do I have to close FileOutputStream which is wrapped by PrintStream?

查看:24
本文介绍了我是否必须关闭由 PrintStream 包装的 FileOutputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 FileOutputStreamPrintStream 一起使用,如下所示:

I'm using FileOutputStream with PrintStream like this:

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

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

I'm closing only the PrintStream. Do I need to also close the FileOutputStream (out.close();)?

推荐答案

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

No, you only need to close the outermost stream. It will delegate all the way to the wrapped streams.

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

However, your code contains one conceptual failure, the close should happen in finally, otherwise it's never closed when the code throws an exception between opening and closing.

例如

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

(注意我把代码改成了抛出异常,这样你就明白了问题的原因,异常即包含了问题原因的详细信息)

(note that I changed the code to throw the exception so that you understand the reason of the problem, the exception namely contains detailed information about the cause of the problem)

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

Or, when you're already on Java 7, then you can also make use of ARM (Automatic Resource Management; also known as try-with-resources) so that you don't need to close anything yourself:

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

这篇关于我是否必须关闭由 PrintStream 包装的 FileOutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆