下载csv内存爆掉解决方案

今天一个下载csv功能测试的时候内存爆掉了代码如下:

File file = new File(tempCsvDir+File.separator+filename+".csv");

            InputStream fis = new BufferedInputStream(new FileInputStream(file));

            byte[] buffer = new byte[fis.available()];

            fis.read(buffer);

            fis.close();

// 清空response

            response.reset();

// 设置response的Header

            response.addHeader("Content-Disposition", "attachment;filename=" + new String((new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"xxx.csv").getBytes()));

            response.addHeader("Content-Length", "" + file.length());

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

            response.setContentType("application/octet-stream");

            toClient.write(buffer);

            toClient.flush();

            toClient.close();

后面在网上找到答案:修改后好了

循环读取

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024 * 1024 * 8];
int i = -1;
while ((i = fis.read(buffer)) != -1) {
    toClient.write(buffer, 0, i);
}
fis.close();        
toClient.flush();
toClient.close();

猜你喜欢

转载自weihong01267.iteye.com/blog/2336771