废话少说,上干货!!
项目中下载小文件或者下载成zip文件都正常,但下载超过2g的zip文件,报错:out of memory:java heap space。
内存溢出,可是大毛病,排查一下代码:
private void setbytearrayoutputstream(string filename, inputstream inputstream, ziparchiveoutputstream zous) {
bytearrayoutputstream baos = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputstream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.flush();
byte[] bytes = baos.tobytearray();
//设置文件名
archiveentry entry = new ziparchiveentry(filename);
zous.putarchiveentry(entry);
zous.write(bytes);
zous.closearchiveentry();
baos.close();
}细心的童鞋应该已经发现错误了!
一、原因分析
原因分析主要与 bytearrayoutputstream 的使用有关。bytearrayoutputstream 会在内存中动态扩展其缓冲区以容纳写入的数据。当写入大量数据时,尤其是在处理大文件时,可能会导致内存频繁分配和复制,从而消耗大量内存。大文件处理:如果输入流(inputstream)读取的数据量很大(如超过几百mb或gb),bytearrayoutputstream 可能会消耗超过可用内存的资源,导致 outofmemoryerror。
在上述代码中,逻辑如下:
(1)读取数据:通过 inputstream.read(buffer) 持续将数据读取到缓冲区 buffer 中。
(2)写入 bytearrayoutputstream:每次读取的数据都被写入到 bytearrayoutputstream 中。如果文件非常大,bytearrayoutputstream 将不断扩展其内部数组。
(3) 转换为字节数组:调用 baos.tobytearray() 时,会创建一个新的字节数组并将所有数据复制到这个新数组中,这又需要额外的内存。
二、解决方案
采用流式处理:直接从 inputstream 读取并写入到 ziparchiveoutputstream,而不使用 bytearrayoutputstream。这样可以避免将整个文件加载到内存中。
代码如下:
private void setbytearrayoutputstream(string filename, inputstream inputstream, ziparchiveoutputstream zous) {
//创建zip入口
try {
ziparchiveentry entry = new ziparchiveentry(filename);
zous.putarchiveentry(entry);
//使用流缓冲区,一次1024字节,分块读取并写入zip输出流
byte[] buffer = new byte[1024];
int len;
while ((len = inputstream.read(buffer)) != -1) {
zous.write(buffer, 0, len);
}
//完成当前zip入口
zous.closearchiveentry();
} catch (exception ex) {
ex.printstacktrace();
} finally {
//确保输入流被关闭
try {
inputstream.close();
} catch (exception e) {
e.printstacktrace();
}
}
}运行之后,我们发现:不论多大的文件下载,不再报错内存溢出了。但对于超过了4g的文件,在形成zip包时,出现了其他错误,如下:
org.apache.commons.compress.archivers.zip.zip64requiredexception: xxxxxxxxxxxxxxxxxxxxxxxxxxxx's size exceeds the limit of 4gbyte. at org.apache.commons.compress.archivers.zip.ziparchiveoutputstream.checkifneedszip64(ziparchiveoutputstream.java:651) at org.apache.commons.compress.archivers.zip.ziparchiveoutputstream.handlesizesandcrc(ziparchiveoutputstream.java:638) at org.apache.commons.compress.archivers.zip.ziparchiveoutputstream.closearchiveentry(ziparchiveoutputstream.java:513)
原因分析:
这个异常通常是在尝试创建一个 zip 文件时遇到的,特别是当文件的大小超过 4gb 时。zip 格式的标准限制了单个文件的大小为 4gb,因此在处理大文件时需要使用 zip64 格式。我们在代码里添加如下:
zous.setusezip64(ziparchiveoutputstream.zip64mode.always); // 启用 zip64 支持 或者(不同版本,函数不一样) zous.setusezip64(zip64mode.always);
按照以上改完之后,我们发现文件下载zip完全没有内存溢出错误了。
到此这篇关于java文件下载zip报错:out of memory的问题排查的文章就介绍到这了,更多相关java文件下载zip报错内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论