读取输入流两次 [英] Read input stream twice
本文介绍了读取输入流两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您如何两次读取相同的输入流?有可能以某种方式复制它吗?
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 thought it would be faster to use the same stream instead of starting a new stream to the downloaded content and then read it again.
推荐答案
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);
yourReadMethodHere(bais);
}
// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
bais.reset();
yourReadMethodHere(bais);
}
这篇关于读取输入流两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文