0

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?

AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76

1 Answers1

0

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(), notwriteAndClose().

Write your own writeAndClose() function.

public static void writeAndClose(String path, Byte[] bytes)
{
    FileOutputStream fos = new FileOutputStream(path)
    IOUtils.write(bytes, fos);
    fos.close();
}
  • I fully understand the reasons, my question was if there are other methods for this, and if there aren't any - why. Jon Skeet gave a good core java solution – AdamSkywalker Mar 11 '16 at 13:55
  • The statements "I fully understand the reasons" and "if there aren't any - why" are contradictory. –  Mar 11 '16 at 13:57
  • what was the reason not to introduce method writeAndClose in IOUtils? – AdamSkywalker Mar 11 '16 at 13:58
  • Questions of the type "why not introduce method X in package Y" make no sense because none of us are part of the package's dev team. For sake of completeness, the answer to your question is bullet point 2 in my answer. –  Mar 11 '16 at 14:00