在 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
What is the best way to make a copy of an InputStream in java
提问by Ankur
Possible Duplicate:
How to make a deep copy of an InputStream in Java ?
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 InputStream
in a BufferedInputStream
, and then use the BufferedInputStream
mark()
and reset()
methods. The InputStream
you have will probably not support them directly, since as far as I understood it receives data from the web.
如果您希望能够再次读取流,我认为您最好的选择是将 包装InputStream
在 a 中BufferedInputStream
,然后使用BufferedInputStream
mark()
和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,因此额外的依赖不会受到影响:
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)
但是请注意,您不能真正“复制”流。您只能“使用”它(然后可以将内容存储在内存中,如果您愿意的话)