What is the best way to make a copy of an InputStream in java [duplicate]
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 we开发者_高级运维b 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?
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.
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)
精彩评论