1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public static void zip(File srcDir, File dstFile) throws Exception { dstFile.delete(); CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(dstFile), new CRC32());
ZipOutputStream zos = new ZipOutputStream(cos); compress(srcDir, zos, ""); zos.flush(); zos.close(); }
private static void compress(File srcFile, ZipOutputStream zos, String basePath) throws Exception { if (srcFile.isDirectory()) { compressDir(srcFile, zos, basePath); } else { compressFile(srcFile, zos, basePath); } }
private static void compressDir(File dir, ZipOutputStream zos, String basePath) throws Exception { File[] files = dir.listFiles(); if (files.length < 1) { ZipEntry entry = new ZipEntry(basePath + dir.getName() + "/"); zos.putNextEntry(entry); zos.closeEntry(); } for (File file : files) { compress(file, zos, basePath + dir.getName() + "/"); } }
private static void compressFile(File file, ZipOutputStream zos, String basePath) throws Exception { String name = basePath + file.getName(); String[] names = name.split("/");
StringBuilder builder = new StringBuilder(); if (names.length > 1) { for (int i = 1; i < names.length; i++) { builder.append("/"); builder.append(names[i]); } } else { builder.append("/"); }
ZipEntry entry = new ZipEntry(builder.toString().substring(1)); zos.putNextEntry(entry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int count; byte data[] = new byte[1024]; while ((count = bis.read(data, 0, 1024)) != -1) { zos.write(data, 0, count); } bis.close(); zos.closeEntry(); }
|