简体   繁体   English

在IOUtils方法中自动关闭流

[英]Auto-close for streams in IOUtils methods

Apache commons-io library is almost a de-facto way for IO operations in java. Apache commons-io库几乎是Java中IO操作的事实上的方法。 What really bothers me is that it does not provide methods for automatically stream closing after io operations. 真正困扰我的是,它不提供io操作后自动关闭流的方法。

Desired workflow: 所需的工作流程:

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

Current workflow: 当前的工作流程:

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

Can I do it in one line? 我可以一行吗? What alternatives do I have? 我有什么选择? If nothing is available, why? 如果什么都没有,为什么?

There are several reasons: 有以下几个原因:

  • Some other workflows still have references to that stream and may want to write to it in the near future. 其他一些工作流程仍然引用该流,并且可能希望在不久的将来对其进行写入。 There is no way for IOUtils to know this information. IOUtils无法知道此信息。 Closing a stream in such a way might create undesired behaviour very quickly. 以这种方式关闭流可能会很快产生不良行为。

  • IO operations should be atomic. IO操作应该是原子的。 write() writes to stream and close() closes it. write()写入流,然后close()关闭。 There is no reason to do both things at the same time, especially if the methods's name explicitly says write() , not writeAndClose() . 没有理由同时做这两件事,尤其是如果方法的名称显式地表示write()而不是writeAndClose()

Write your own writeAndClose() function. 编写自己的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