javainputstreamdatainputstream

How do I check that an InputStream has been consumed?


I'm working on a task and have had a question on the code review- 'do we need to ensure the input stream is consumed here?'

public void processInputStream(final DataInputStream dataInputStream, final OutputStream output) {
        try {
            // doing something with dataInputStream!!
        } catch (IOException e) {
            // doing something with IOException
        }
}

I have a few questions -

#1 I assume that if the InputStream processing is interrupted, then my catch block will be triggered. Is that correct? And if so, does that negate the need to ensure that the stream has been consumed?

#2 How would I check the InputStream has been consumed in this case?

Thanks

Update -

Part of processing my InputStream involves using -

copyInputStreamToFile(..)

From Apache commons https://commons.apache.org/proper/commons-io/javadocs/api-2.7/org/apache/commons/io/FileUtils.html#copyInputStreamToFile-java.io.InputStream-java.io.File-

Their documentation says -

Copies bytes from an InputStream source to a file destination. The directories up to destination will be created if they don't already exist. destination will be overwritten if it already exists. The source stream is closed. See copyToFile(InputStream, File) for a method that does not close the input stream.

Does this mean that given the source stream is closed, then this covers checking the InputStream has been consumed?


Solution

  • This did the trick!

    private void consumeQuietly(final InputStream inputStream) {
        try (OutputStream out = NullOutputStream.NULL_OUTPUT_STREAM) {
            IOUtils.copy(inputStream, out);
        } catch (IOException ioException) {
            // Log something!!
        }
    }