電子書項目需解壓 EPUB 文件(本質是 ZIP),大文件解壓後內存飆升 40MB+,易導致 OOM。
不將整個解壓內容載入內存,而是邊讀邊寫,使用固定大小 byte 數組(如 1MB)作為緩衝區。
public static void unZip(Context context, String assetName, String outputDirectory) throws IOException {
File srcFile = new File(FileTools.getStoragePath(context, false) + "/" + assetName);
File destDir = new File(outputDirectory);
if (!destDir.exists()) destDir.mkdirs();
try (FileInputStream fis = new FileInputStream(srcFile);
ZipInputStream zis = new ZipInputStream(fis)) {
byte[] buffer = new byte[1024 * 1024]; // 1MB 緩衝區
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outFile = new File(destDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
outFile.getParentFile().mkdirs(); // 確保父目錄存在
try (FileOutputStream fos = new FileOutputStream(outFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zis.closeEntry();
}
}
}
getParentFile().mkdirs() 確保嵌套目錄存在。RandomAccessFile + 多線程分段解壓。