rozerro rozerro - 4 months ago 28
Java Question

IOUtils: is it required to close OutputStream?

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?

Answer

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.

Comments