如何检查 InputStream 是否已被使用?

How do I check that an InputStream has been consumed?

我正在处理一项任务,对代码审查有疑问- '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
        }
}

我有几个问题-

#1 我假设如果 InputStream 处理被中断,那么我的 catch 块将被触发。 那是对的吗?如果是这样,是否不需要确保流已被消耗?

#2 在这种情况下,如何检查 InputStream 是否已被消耗?

谢谢

更新-

处理我的 InputStream 的一部分涉及使用 -

copyInputStreamToFile(..)

来自 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-

他们的文档说 -

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.

这是否意味着如果源流已关闭,那么这将涵盖检查 InputStream 是否已被消耗?

您可以使用此方法检查 InputStream 是否已耗尽:

package example;

import java.io.IOException;
import java.io.InputStream;

public class SO {

    public static boolean isExhausted(InputStream in) throws IOException {
        final boolean exhausted;

        if (in.markSupported()) {
            in.mark(1);
            exhausted = in.read() == -1;
            in.reset();
        } else {
            throw new IllegalStateException("mark is not supported on this inputstream");
        }

        return exhausted;
    }
}

请注意,这仅在 InputStream 支持标记和重置方法时有效 (in.markSupported())

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

    }
    catch (IOException ioe)
    {
        // doing something with IOException
    }
}

可以利用inputStream.available()方法判断输入流是否被消费。

成功了!

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