繁体   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