Properly closing Java Process InputStream from getInputStream

Bob picture Bob · Aug 17, 2011 · Viewed 10.8k times · Source

I could not find clarification of this in the documentation. But when we have a Process object and call getInputStream(),

Do we get a new stream that we should explicitly close when we are done with it? or do we get the stream that is already there, associated with the Process, that we should not close, but the Process would take care of closing it?

Basically, how should we interact with the stream we get from Process.getInputStream()? close or not to close?

Answer

Ali picture Ali · Aug 17, 2011

My first reactions was to close it, you always close streams that you open. I do realize the documentation is not up to par, but since they don't explicitly state do not close that to me means follow good programming practices.

InputStream is = process.getInputStream()
try {
    // your code
} finally {
    try { is.close(); } catch (Exception ignore) {}
}

If you need to make sure this isn't problematic, just write a quick test case where you great from the input stream a few dozen times, each time opening and closing the InputStream.