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

Possible duplicate:
How to make a deep copy of 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 does not come from the file, but as the payload of the http form sent from the web page, I use the Apache Commons FileUpload library, my code that InputStream gives me 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 duplicate / copy of imageStream?

+6
java inputstream copy
source share
2 answers

If you want 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. InputStream you have will probably not support them directly, since, as I understand it, it receives data from the Internet.

+5
source share

The best way to "copy" your input stream is to use commons-io. Since you are using file sharing, this additional dependency will not hurt:

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

Remember that you cannot "copy" a stream. You can "consume" it (and then, perhaps, keep the contents in memory if you want)

+1
source share

All Articles