Alexandru Severin Alexandru Severin - 1 year ago 57
Java Question

Coping file from inputstream to outputstream results in bad copy

I made an upload file servlet, summed up like this:

ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item =;
InputStream stream = item.openStream()
File file = new File(path +"/"+ item.getFieldName));

FileOutputStream fout= new FileOutputStream (file);
BufferedOutputStream bout= new BufferedOutputStream (fout);
BufferedInputStream bin= new BufferedInputStream(stream);
byte buf[] = new byte[2048];
while (( != -1){

I used streams so that the file isn't loaded in memory.

The files are being uploaded smoothly, but I cannot open the resulted file (error differs depending on file type). Also the size of the resulted file is larger then the one of the original.

I tried different types of stream readers and writers but couldn't get any closer, and I couldn't find a similar problem.
I ruled out encoding as I am receiving and writing bytes, so encoding doesn't matter, right?

What could be the problem?

Answer Source

You're writing all the content of buf array. This could be the problem for last read.

Change the while loop like this:

int n;
while ((n = != -1)
    bout.write(buf, 0, n);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download