问题描述
如何读取相同的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.
推荐答案
您可以使用<$c$c>org.apache.commons.io.IOUtils.copy$c$c>到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);
}
这篇关于读取数据流的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!