Csv文件在下载时写入额外的行

时间:2017-11-15 07:46:39

标签: java csv jsp servlets

当我尝试从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();
    }
}

1 个答案:

答案 0 :(得分:1)

实际上getDownloaded方法存在一个微妙的错误。这里的代码最终会读取写入不正确的字节数,以防少于4096字节被读取,因此可能会向外流写入垃圾:

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

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

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