實測:4.76 GB一個單文件壓縮沒有什么問題。
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; public class ZipHelper { public static void main(String[] args) { File[] files=new File[1]; File tmpFile=new File("F:\\ios10.8.2\\macos.dmg"); files[0] = tmpFile; File zipFile=new File("F:\\ios10.8.2\\test.zip"); ZipHelper.zipFiles(files, zipFile); } public static boolean zipFiles(File[] files, File zipFile) { boolean flag = false; if (files != null && files.length > 0) { ZipArchiveOutputStream zaos = null; try { zaos = new ZipArchiveOutputStream(zipFile); // Use Zip64 extensions for all entries where they are required zaos.setUseZip64(Zip64Mode.AsNeeded); // 將每個文件用ZipArchiveEntry封裝 // 再用ZipArchiveOutputStream寫到壓縮文件中 for (File file : files) { if (file != null) { ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName()); zaos.putArchiveEntry(zipArchiveEntry); InputStream is = null; try { is = new FileInputStream(file); byte[] buffer = new byte[1024 * 5]; int len = -1; while ((len = is.read(buffer)) != -1) { // 把緩沖區的字節寫入到ZipArchiveEntry zaos.write(buffer, 0, len); } zaos.closeArchiveEntry(); } catch (Exception e) { flag = false; } finally { if (is != null) is.close(); } } } zaos.finish(); flag=true; } catch (Exception e) { flag = false; } finally { try { if (zaos != null) { zaos.close(); } } catch (IOException e) { flag = false; } } } return flag; } /** * 解壓縮ZIP文件,將ZIP文件里的內容解壓到saveFileDir目錄下 * @param zipFilePath 待解壓縮的ZIP文件名 * @param saveFileDir 目標目錄 */ public static boolean upzipFile(String zipFilePath, String saveFileDir) { boolean flag = false; File file = new File(zipFilePath); if (file.exists()) { InputStream is = null; ZipArchiveInputStream zais = null; try { is = new FileInputStream(file); zais = new ZipArchiveInputStream(is); ArchiveEntry archiveEntry = null; // 把zip包中的每個文件讀取出來 // 然后把文件寫到指定的文件夾 while ((archiveEntry = zais.getNextEntry()) != null) { // 獲取文件名 String entryFileName = archiveEntry.getName(); // 構造解壓出來的文件存放路徑 String entryFilePath = saveFileDir + entryFileName; byte[] content = new byte[(int) archiveEntry.getSize()]; zais.read(content); OutputStream os = null; try { // 把解壓出來的文件寫到指定路徑 File entryFile = new File(entryFilePath); os = new FileOutputStream(entryFile); os.write(content); } catch (IOException e) { flag = false; } finally { if (os != null) { os.flush(); os.close(); } } } flag=true; } catch (Exception e) { flag = false; } finally { try { if (zais != null) { zais.close(); } if (is != null) { is.close(); } } catch (IOException e) { flag = false; } } } return flag; } }