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

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

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

最佳答案

不需要,只需要关闭最外层的流即可。它将一直委托(delegate)给包装流。

但是,您的代码包含一个概念上的错误,关闭应该发生在 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(自动资源管理;也称为 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;
    }
}

关于java - 我是否必须关闭由 PrintStream 包装的 FileOutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8080649/

相关文章:

java.lang.OutOfMemory错误: Java heap space ("-Xmx1280M")

java - 读取jar中的文件

javascript - 任何适用于 iOS 的 WebRTC 客户端实现?

c - Eclipse 中 printf() 的不明确行为

stream - 关于流媒体,像 Skype 这样的程序如何工作?

c# - C# 中的流右移运算符等效吗?

java - 对于一个完整的 Scala 新手来说,基于 Scala 的框架如何堆叠起来——Lift、Play、Circumflex 等

java - JPA @OneToMany 具有复合 PK - PK/FK 重叠

c - 连续扫描流缓冲区中字符串的最佳方法

java - 将数据从对话框传递到 Android Activity