如何在java中下载大文件而不会出现内存问题
2022-09-02 12:34:02
当我尝试从服务器下载260MB的大文件时,我收到此错误:我确定我的堆大小小于252MB。有没有办法在不增加堆大小的情况下下载大文件?java.lang.OutOfMemoryError: Java heap space.
如何在不遇到此问题的情况下下载大文件?我的代码如下:
String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {
File file = new File(path);
long length = file.length();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
ServletOutputStream out = response.getOutputStream();
while ((in != null) && ((length = in.read(buf)) != -1)) {
out.write(buf, 0, (int) length);
}
in.close();
out.close();