【问题标题】:Coping file from inputstream to outputstream results in bad copy将文件从输入流复制到输出流会导致复制错误
【发布时间】:2015-05-14 16:55:48
【问题描述】:

我做了一个上传文件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();
}

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

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

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

可能是什么问题?

【问题讨论】:

    标签: java file servlets upload


    【解决方案1】:

    您正在编写 buf 数组的所有内容。这可能是最后一次阅读的问题。

    像这样更改while 循环:

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

    【讨论】:

      猜你喜欢
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多