我正在尝试使用以下代码下载超过100mb的视频mp4文件。但我得到" java.lang.OutOfMemoryError:Java堆空间"在下载时。
使用jdk1.7& Spring MVC。
我在SO链接下面提到但是没有一个对我有效。
how to download large files without memory issues in java
java.lang.OutOfMemoryError: Java heap space while downloading a large file from an URL
请帮我解决这个问题。
OutputStream outStream = null;
FileInputStream inputStream = null;
try {
ServletContext context = request.getSession().getServletContext();
String fileName = Integer.toString(fileId);
filePath = fileName+".mp4";
File downloadFile = new File(filePath);
inputStream = new FileInputStream(new File(filePath));
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
outStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0, bytesBuffered = 0;
while((bytesRead = inputStream.read(buffer)) > -1) {
outStream.write(buffer, 0, bytesRead);
bytesBuffered += bytesRead;
if (bytesBuffered > 1024 * 1024) { //flush after 1MB
bytesBuffered = 0;
outStream.flush();
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
答案 0 :(得分:2)
我尝试使用500 MB文件下面的代码并没有收到内存不足错误
OutputStream outStream = response.getOutputStream();
String mimeType = "application/zip";
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
"abc.zip");
response.setHeader(headerKey, headerValue);
response.setContentType(mimeType);
response.setStatus(HttpServletResponse.SC_OK);
File downloadFile = new File("file path");
InputStream inputStream = new FileInputStream(downloadFile);
int n = 0;
byte[] buf = new byte[1024];
while ((n = inputStream.read(buf)) != -1) {
outStream.write(buf, 0, n);
}
inputStream.close();
outStream.flush();
outStream.close();
和JVM设置为:
-XX:PermSize=256m
-XX:MaxPermSize=512m
-Xms1024m
-Xmx2048m
-Dosgi.requiredJavaVersion=1.8
-XX:+UseG1GC
-XX:+UseStringDeduplication
答案 1 :(得分:0)
您需要致电HttpServletResponse.flushBuffer()
,而不仅仅是OutputStream.flush()
,而且更频繁。