读取数据流的两倍 [英] Read stream twice

查看:181
本文介绍了读取数据流的两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取相同的InputStream两次?是否有可能以某种方式复制?

How do you read the same inputstream twice? Is it possible to copy it somehow?

我需要从网络获得图像,将其保存在本地,然后返回保存的图像。我刚因子评分将是更快地使用开始一个新的流,以所下载的内容的相同的流,而不是,然后再次读取。

I need to get a image from web, save it locally and then return the saved image. I just tought it would be faster to use the same stream instead of starting a new stream to the downloaded content and then read it again.

推荐答案

您可以使用<一个href="http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29"><$c$c>org.apache.commons.io.IOUtils.copy到InputStream中的内容复制到一个字节数组,然后使用一个ByteArrayInputStream字节数组反复读。例如:

You can use org.apache.commons.io.IOUtils.copy to copy the contents of the InputStream to a byte array, and then repeatedly read from the byte array using a ByteArrayInputStream. E.g.:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();

// either
while (needToReadAgain) {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    read(bais);
}

// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
    bais.reset();
    read(bais);
}

这篇关于读取数据流的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆