执行操作后丢失 InputStream 中的内容

问题描述

我正在使用外部扫描工具执行数据检查。在这个过程中,我将 InputStream 传递给了扫描工具。该工具扫描流并使用布尔值进行响应。使用这个布尔值,我将决定是否要将流保存到文件中。在此过程中,该工具不会重置输入流,而是处于 EOF 状态。这使它无法使用。因此,我正在创建的文件将有 0 个字节。

我无法改变正在执行此操作的工具。所以我需要找到一种不影响 InputStream 内容方法。但同时对Input Stream进行扫描和写入。

这是我的代码

    FileOutputStream fos = null;
    ReadableByteChannel rbc = null;
    try {
        log.info(masterId + " : DOWNLOADING FILE FROM [ " + url + " ]");

        HttpURLConnection httpcon = (HttpURLConnection) urlConnection;
        //rbc = Channels.newChannel(httpcon.getInputStream());  -- this was my another approach
        //InputStream inputStream = Channels.newInputStream(rbc);
        if (!scanTool.scan(IoUtils.toByteArray(httpcon.getInputStream()))) {
            // exit with fail code
        }
        rbc = Channels.newChannel(httpcon.getInputStream());
        fos = new FileOutputStream(filePath);
        fos.getChannel().transferFrom(rbc,Long.MAX_VALUE);
        fos.close();
        rbc.close();
        return 1;
    } catch (FileNotFoundException ex) {
        //Handle exception
    }

在上面的代码片段中,

        if (!scanTool.scan(IoUtils.toByteArray(httpcon.getInputStream()))) {
            // exit with fail code
        }

这是我的新插入。我正在调用 scanTool 来执行检查条件的操作,只有当它通过时才继续写入文件。现在,在执行此操作时,我丢失了 inputStream 中的内容

在这里错过了什么。我什至尝试使用 BufferedInputSteam。仍然没有锻炼。还尝试了另一种方法,我构造新的可读字节通道,然后从中构造新的 InputStream。如注释代码所示。但是没有水果。

解决方法

鉴于您已经将 InputStream 转换为 byte[],您可以在扫描后写出相同的字节数组:

byte[] bytes = IOUtils.toByteArray(httpcon.getInputStream());
if (!scanTool.scan(bytes)) {
        // exit with fail code
}
try(FileOutputStream fos = new FileOutputStream(filePath)) {
    fos.write(bytes);
}