![](/img/trans.png)
[英]If I close ObjectOuputStream, then do not need to close FileOutputStream?
[英]Do I have to close FileOutputStream which is wrapped by PrintStream?
我正在使用FileOutputStream
和PrintStream
如下所示:
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();
)?
不,你只需要關閉最外面的流。 它將一直委托給包裝的流。
但是,您的代碼包含一個概念上的失敗,close應該在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;
}
}
不,這是PrintStream
的close()
方法的實現:
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();
它關閉輸出流。
不,你不需要。 PrintStream.close方法自動關閉下划線輸出流。
檢查API。
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#close%28%29
不,根據javadoc,close方法將為您關閉底層流。
不需要。不需要關閉其他組件。 關閉流時,它會自動關閉其他相關組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.