当我试图从服务器下载一个 260MB 的大文件时,我得到这个错误:java.lang.OutOfMemoryError: Java heap space.
我确定我的堆大小小于252MB。有什么方法可以在不增加堆大小的情况下下载大文件?
如何下载大文件而不会出现此问题?我的代码如下:
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();
最佳答案
有 2 个地方我可以看到您可能会增加内存使用量:
- 在缓冲区中读取您的输入文件。
- 在缓冲区中写入您的输出流(HTTPOutputStream?)
对于 #1,我建议直接通过 FileInputStream
读取文件,而不使用 BufferedInputStream
。先试试这个,看看它是否能解决您的问题。即:
FileInputStream in = new FileInputStream(file);
代替:
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
如果 #1 不能解决问题,您可以尝试在写入这么多数据后定期刷新输出流(如有必要,减小块大小):
即:
try
{
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buf=new byte[8192];
int bytesread = 0, bytesBuffered = 0;
while( (bytesread = fileInputStream.read( buf )) > -1 ) {
out.write( buf, 0, bytesread );
bytesBuffered += bytesread;
if (bytesBuffered > 1024 * 1024) { //flush after 1MB
bytesBuffered = 0;
out.flush();
}
}
}
finally {
if (out != null) {
out.flush();
}
}
关于java - 如何在java中下载没有内存问题的大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7106775/