【问题标题】:Csv file writing the extra rows while downloading下载时写入额外行的 CSV 文件
【发布时间】:2017-11-15 07:46:38
【问题描述】:

当我尝试从 servlet 代码导出 csv 文件时,它显示了正确的记录,但最后它显示了额外的行。

示例:它需要 1000 行,但它显示 1041 行长,有 1000 条记录。

下面是我的代码和excel表格。

// for downloading csv
public void getDownloaded(String filepath, HttpServletResponse response) {
    try {
        File file = new File(filepath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] outputByte = new byte[4096];
        // copy binary content to output stream
        while (in.read(outputByte, 0, 4096) != -1) {
            out.write(outputByte, 0, 4096);
        }
        in.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 您在本地服务器目录目录中看到getCSVWrite 方法生成的文件了吗?

标签: java csv jsp servlets


【解决方案1】:

实际上getDownloaded 方法中有一个微妙的错误。此处的代码最终会读取并写入不正确的字节数,以防读取的字节数少于 4096,因此可能会将垃圾写入输出流:

//copy binary content to output stream
while(in.read(outputByte, 0, 4096) != -1){
    out.write(outputByte, 0, 4096);
}

它实际上应该在写语句中使用确切的读取字节数:

int length;
while ((length = in.read(outputByte, 0, 4096)) != -1) {
    out.write(outputByte, 0, length);
}

【讨论】:

  • 感谢@gil.fernandes
猜你喜欢
  • 2014-06-08
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2018-01-27
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多