rozerro rozerro - 3 months ago 8x
Java Question

IOUtils: is it required to close OutputStream?

In this answer, a guy suggested using

but he did not close OutputStream. Here's his example:

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

IOUtils.copy(is, os);

I checked javadocs for the
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?


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.