Issue
When I try to export the csv file from servlet code it displayed the correct records but at the end it display extra rows.
Example: It need 1000 rows but it display 1041 rows long with 1000 records.
Below is my code and the excel sheet.
// 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();
}
}
Solution
Actually there is a subtle bug in the getDownloaded
method. This code here reads eventually an writes an incorrect number of bytes in case less than 4096 bytes are read, thus writing potentially garbage to the out stream:
//copy binary content to output stream
while(in.read(outputByte, 0, 4096) != -1){
out.write(outputByte, 0, 4096);
}
It should actually use the exact number of read bytes in the write statement:
int length;
while ((length = in.read(outputByte, 0, 4096)) != -1) {
out.write(outputByte, 0, length);
}
Answered By - gil.fernandes