如何在 Java 中制作输入流的深层复制

发布于 2024-09-30 00:24:05 字数 1431 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2024-10-07 00:24:05

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

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

如果您在 InputStream 上使用 mark() 那么您确实无法逆转这一点。这会使您的流被“消耗”。

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

已编辑:

顺便说一句,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;
 }

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文