簡體   English   中英

在IOUtils方法中自動關閉流

[英]Auto-close for streams in IOUtils methods

Apache commons-io庫幾乎是Java中IO操作的事實上的方法。 真正困擾我的是,它不提供io操作后自動關閉流的方法。

所需的工作流程:

IOUtils.write(myBytes, new FileOutputStream("/path/to/file.txt"));

當前的工作流程:

FileOutputStream fos = new FileOutputStream("/path/to/file.txt")
IOUtils.write(myBytes, fos);
fos.close();

我可以一行嗎? 我有什么選擇? 如果什么都沒有,為什么?

有以下幾個原因:

  • 其他一些工作流程仍然引用該流,並且可能希望在不久的將來對其進行寫入。 IOUtils無法知道此信息。 以這種方式關閉流可能會很快產生不良行為。

  • IO操作應該是原子的。 write()寫入流,然后close()關閉。 沒有理由同時做這兩件事,尤其是如果方法的名稱顯式地表示write()而不是writeAndClose()

編寫自己的writeAndClose()函數。

public static void writeAndClose(String path, Byte[] bytes)
{
    FileOutputStream fos = new FileOutputStream(path)
    IOUtils.write(bytes, fos);
    fos.close();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM