在创建csv文件时,该文件在控制器中有额外的记录

时间:2016-02-26 09:12:24

标签: java

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=download.csv");

sb = Dataretriver.generateCsvFileBuffer(Fields,fieldsForm.getRowNum());

System.out.println("--this will generates csv file format");

InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));

byte[] outputByte = new byte[4096];

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

in.close();
out.close();

在创建文件时,我获得了更多记录(不完全是我给出的记录数。)

请建议我解决此问题

1 个答案:

答案 0 :(得分:1)

你有一个字符串。此String可以转换为字节。并且您希望将这些字节发送到响应输出流。

而不是在字节数组上使用InputStream,在循环中读取块,并以不正确的方式写入每个块(最后一个块很可能没有正好4096个字节,read()不保证读取4096字节:它可以读取更少),只需将字节直接写入输出流:

out.write(sb.toString().getBytes("UTF-8"));