读取输入流两次 [英] Read input stream twice

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

问题描述

如何读取相同的输入流两次?是否可以以某种方式复制它?

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

我需要从 Web 获取图像,将其保存在本地,然后返回保存的图像.我只是认为使用相同的流而不是开始一个新的流到下载的内容然后再次阅读它会更快.

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.

推荐答案

您可以使用 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);
    yourReadMethodHere(bais);
}

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

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

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