如何在 Java 中制作 InputStream 的深层副本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4064211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:37:50  来源:igfitidea点击:

How to make a deep copy of an InputStream in Java

javacloneinputstreamdeep-copy

提问by Spredzy

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

我想知道如何制作InputStream.

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?

我知道它可以用 IOUtils 包来完成,但我想尽可能避免它们。有谁知道另一种方法?

回答by Peter Knego

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:

InputStream 是抽象的并且不公开(也不公开其子代)内部数据对象。因此,“深度复制” InputStream 的唯一方法是创建 ByteArrayOutputStream,然后在 InputStream 上执行 read() 之后,将此数据写入 ByteArrayOutputStream。然后做:

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".

如果您mark()在 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.

要“重用”您的 InputStream,请避免使用 mark(),然后在阅读结束时调用 reset()。然后,您将从流的开头开始阅读。

Edited:

编辑:

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

顺便说一句,IOUtils 使用这个简单的代码片段来复制 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

阅读更多:http: //kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m