在java中复制InputStream的最佳方法是什么
可能的重复:
如何在Java?
我有一个 InputStream 对象,我想复制它。最好的方法是什么?
数据不是来自文件,而是作为从网页发送的 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();
}
}
什么是最好的获取 imageStream 的副本/副本的方法?
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?
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: ...
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望能够再次读取流,我认为最好的选择是将
InputStream
包装在BufferedInputStream
中,然后使用BufferedInputStream
code>mark()
和reset()
方法。您拥有的InputStream
可能不会直接支持它们,因为据我了解它从网络接收数据。If you want to be able to read the stream again, I think your best option is to wrap the
InputStream
in aBufferedInputStream
, and then use theBufferedInputStream
mark()
andreset()
methods. TheInputStream
you have will probably not support them directly, since as far as I understood it receives data from the web.“复制”输入流的最佳方法是使用 commons-io。由于您已经使用了 commons fileupload,因此额外的依赖项不会造成伤害:
http://commons.apache.org /io/
但请注意,您无法真正“复制”流。您只能“使用”它(然后可以将内容存储在内存中,如果您愿意的话)
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:
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)