2

In this answer, a guy suggested using IOUtils.copy but he did not close OutputStream. Here's his example:

InputStream is = new URL(imgUrl).openStream();
OutputStream os = servletResponse.getOutputStream();

IOUtils.copy(is, os);
is.close();

I checked javadocs for the copy method in IOUtils and there is no information that OutputStream will be closed automaticaly so I'm curious is it required to close OutputStream in that sample?

Community
  • 1
  • 1
rozerro
  • 5,787
  • 9
  • 46
  • 94
  • If you do intend to close your resource or steam, make sure to call `close()` from within a `finally` block to make sure that it gets executed at all times. Alternatively, open your resource in a [try-with-resources statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – matsev Jul 17 '16 at 11:12

2 Answers2

3

IOUtils.copy(InputStream, OutputStream) must not close the OutputStream. You can use it for example to concatenate different InputStreams and in this case it would be a bad idea if it would close the provided Input- and/or OutputStream.

As a rule of thumb any method should close only those steams it opens. See also Should I close the servlet outputstream?

Community
  • 1
  • 1
andih
  • 5,570
  • 3
  • 26
  • 36
1

As you say, the documentation says nothing about closing the OutputStream for you, so you need to close it (explicitly, or by using try-with-resources).

The reason Tomasz didn't close the stream in that answer was that it's the output stream of a servlet response. As andih said in a comment, you only close streams you open. The servlet container manages the servlet response stream.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    **Don't** close the OutputStream of a ServletResponse. You should only close Streams you've opened. See also: http://stackoverflow.com/questions/1829784/should-i-close-the-servlet-outputstream – andih Jul 17 '16 at 09:04
  • Indeed, a quick glance at the source code *confirms* that `IOUtils.copy` does NOT close either stream. – Stephen C Jul 17 '16 at 09:06