对于Large文件,在标记inputStream并重置它时会出现“重置为无效标记”的异常。

时间:2013-09-02 12:51:08

标签: java file-io inputstream

我正在使用InputStream对象来计算某个文件的Md5。 我标记了流 后来我重置了流。但是对于大文件,会出现以下异常......

inStreamLatestFile.mark(0);
checkSumCalculated = MD5CheckSumCalculator.calculateMD5CheckSum(inStreamLatestFile);
inStreamLatestFile.reset();

例外

.Md5ValidationAggrStrat ||**Error in calculating checksum:: java.io.IOException: Resetting to invalid mark**
                        ||java.io.IOException: Resetting to invalid mark
                        ||at java.io.BufferedInputStream.reset(BufferedInputStream.java:437)
                        ||at com.amadeus.apt.ib.modules.func.map.camel.strategy.Md5ValidationAggrStrategy.aggregate(Md5ValidationAggrStrategy.java:81)
                        ||at org.apache.camel.processor.aggregate.AggregateProcessor.onAggregation(AggregateProcessor.java:365)
                        ||at org.apache.camel.processor.aggregate.AggregateProcessor.doAggregation(AggregateProcessor.java:245)
                        ||at org.apache.camel.processor.aggregate.AggregateProcessor.process(AggregateProcessor.java:201)
                        ||at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
                        ||at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)

我尝试关闭流并以这种方式重新打开..只是为了得到一些例外,如下所示::

 try {
        inStreamLatestFile= ExchangeHelper.getMandatoryInBody(
                  oldExchange, InputStream.class);

        //inStreamLatestFile.mark(0);
        checkSumCalculated = MD5CheckSumCalculator.calculateMD5CheckSum(inStreamLatestFile);

        //closing the inputStream of the latest file
        if(inStreamLatestFile != null){
            try {
                inStreamLatestFile.close();
            } catch (IOException e) {
                logger.error("Error occurred in closing the stream :: "+ e.getMessage());
            }
        }


        tempInputStream= ExchangeHelper.getMandatoryInBody(
                  oldExchange, InputStream.class);
        oldExchange.getIn().setBody(tempInputStream);

但是,当我尝试重新使用新重新检索的InputStream时会出现以下异常。

 caught: java.io.IOException: Stream closed: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)

1 个答案:

答案 0 :(得分:4)

我假设您使用的是BufferedInputStream,因为reset()方法的源代码是

public synchronized void reset() throws IOException {
    getBufIfOpen(); // Cause exception if closed
    if (markpos < 0)
        throw new IOException("Resetting to invalid mark"); // exception you are getting
    pos = markpos;
}

以下电话

MD5CheckSumCalculator.calculateMD5CheckSum(inStreamLatestFile);

必须对markPos执行某些操作。

如果您无法控制它,只需重新打开该流即可。如果你不能重新打开流,即。您每次都在检索相同的实例,请考虑使用ByteArrayOutputStream

您可以将原始InputStream阅读为ByteArrayOutputStream。将该流中的字节复制到新的ByteArrayInputStream中。将其传递给MD5计算器。然后使用相同的字节再次创建一个新的ByteArrayInputStream,并将其传递给您需要的任何其他内容。