Alexandru Severin Alexandru Severin - 1 month ago 7
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 = iter.next();
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 ((bin.read(buf)) != -1){
bout.write(buf);
}
bout.close();
bin.close();
}


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

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 = bin.read(buf)) != -1)
{
    bout.write(buf, 0, n);
}