如何使Java中的InputStream的深层复制 [英] How to make a deep copy of an InputStream in Java

查看:3085
本文介绍了如何使Java中的InputStream的深层复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使一个深层副本的的InputStream

I would like to know how to make a deep copy of an InputStream.

我知道,它可以与IOUtils包来完成,但我想,以避免他们如果可能的话。 有谁知道一种替代方法?

I know that it can be done with IOUtils packages, but I would like to avoid them if possible. Does anyone know an alternate way?

推荐答案

InputStream的是抽象的,不公开(没有尽自己的孩子)的内部数据对象。所以唯一的办法,以深拷贝InputStream的是创造ByteArrayOutputStream后执行Read()上的InputStream,写(),该数据ByteArrayOutputStream。然后做:

InputStream is abstract and does not expose (neither do its children) internal data objects. So the only way to "deep copy" the InputStream is to create ByteArrayOutputStream and after doing read() on InputStream, write() this data to ByteArrayOutputStream. Then do:

newStream = new ByteArrayInputStream(byteArrayOutputStream.toArray());

如果您使用的是标记()您的InputStream那么你的确不能扭转这一点。这使你流消费。

If you are using mark() on your InputStream then indeed you can not reverse this. This makes your stream "consumed".

要重用你的InputStream避免使用标记(),然后在阅读呼叫复位结束()。您会然后读取来自流的开头。

To "reuse" your InputStream avoid using mark() and then at the end of reading call reset(). You will be then reading from beginning of the stream.

编辑:

顺便说一句,IOUtils使用这个简单的code片段复制的InputStream:

BTW, IOUtils uses this simple code snippet to copy InputStream:

public static int copy(InputStream input, OutputStream output) throws IOException{
     byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
     int count = 0;
     int n = 0;
     while (-1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
         count += n;
     }
     return count;
 }

了解更多:<一href="http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m">http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m

这篇关于如何使Java中的InputStream的深层复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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