在 java 中制作 InputStream 副本的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4526074/
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 06:45:08  来源:igfitidea点击:

What is the best way to make a copy of an InputStream in java

javacopyinputstream

提问by Ankur

Possible Duplicate:
How to make a deep copy of an InputStream in Java ?

可能的重复:
如何在 Java 中制作 InputStream 的深层副本?

I have an InputStream object and I want to make a copy of it. What is the best way to do this?

我有一个 InputStream 对象,我想复制它。做这个的最好方式是什么?

The data is not coming from a file but as the payload of a http form being sent from a web page, I am using the Apache Commons FileUpload lib, my code which gives me the InputStream looks like this: ...

数据不是来自文件,而是作为从网页发送的 http 表单的有效负载,我使用的是 Apache Commons FileUpload 库,我的代码提供了 InputStream,如下所示:...

InputStream imageStream = null;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = new ArrayList();

        items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) { // this is subject Id
                if (item.getFieldName().equals("subId")) {
                    subId = Integer.parseInt(item.getString());
                    System.out.println("SubId: " + subId);
                }
            } else {
                imageStream = item.getInputStream();

            }
        }

What is the best way to get a duplicate/copy of imageStream?

获取 imageStream 副本/副本的最佳方法是什么?

回答by Flavio

If you want to be able to read the stream again, I think your best option is to wrap the InputStreamin a BufferedInputStream, and then use the BufferedInputStreammark()and reset()methods. The InputStreamyou have will probably not support them directly, since as far as I understood it receives data from the web.

如果您希望能够再次读取流,我认为您最好的选择是将 包装InputStream在 a 中BufferedInputStream,然后使用BufferedInputStreammark()reset()方法。在InputStream你有可能不会直接支持他们,因为据我的理解是从网络接收数据。

回答by Lukas Eder

The best way of "copying" your input stream is to use commons-io. Since you're using commons fileupload alread, that additional dependency won't hurt:

“复制”输入流的最佳方式是使用 commons-io。由于您已经使用了 commons fileupload,因此额外的依赖不会受到影响:

http://commons.apache.org/io/

http://commons.apache.org/io/

Be aware though, that you cannot really "copy" a stream. You can only "consume" it (and then maybe store the contents in memory, if you want that)

但是请注意,您不能真正“复制”流。您只能“使用”它(然后可以将内容存储在内存中,如果您愿意的话)