How to make a deep copy of an InputStream in Java [closed]

吃可爱长大的小学妹 提交于 2019-11-29 04:38:05

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());

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

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.

Edited:

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;
 }

Read more: http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!