gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:32:16 32 4
gpt4 key购买 nike

我将 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com