将文件从输入流复制到输出流导致复制错误

Coping file from inputstream to outputstream results in bad copy

我做了一个上传文件的servlet,总结起来是这样的:

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();
}

我使用了流,因此文件不会加载到内存中。

文件正在顺利上传,但我无法打开结果文件(错误因文件类型而异)。此外,结果文件的大小也比原始文件大。

我尝试了不同类型的流读取器和写入器,但无法更接近,也找不到类似的问题。 我在接收和写入字节时排除了编码,所以编码并不重要,对吧?

可能是什么问题?

您正在写入 buf 数组的所有内容。这可能是上次阅读的问题。

像这样更改 while 循环:

int n;
while ((n = bin.read(buf)) != -1)
{
    bout.write(buf, 0, n);
}