简体   繁体   中英

Auto-close for streams in IOUtils methods

Apache commons-io library is almost a de-facto way for IO operations in java. What really bothers me is that it does not provide methods for automatically stream closing after io operations.

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. Closing a stream in such a way might create undesired behaviour very quickly.

  • IO operations should be atomic. write() writes to stream and close() closes it. There is no reason to do both things at the same time, especially if the methods's name explicitly says write() , not writeAndClose() .

Write your own writeAndClose() function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM