实测: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; } }
时间: 2024-11-05 18:27:59