1 2 3 4 5 6 7 | import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; |
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 | public static void compress(File source, File destination) throws IOException{ compress(source, destination, null , Deflater.DEFAULT_COMPRESSION); } public static void compress(File source, File destination, String comment, int level) throws IOException{ ZipOutputStream zos = new ZipOutputStream( new FileOutputStream(destination)); zos.setComment(comment); zos.setLevel(level); compress(zos, source.getParent(), source); zos.flush(); zos.close(); } private static void compress(ZipOutputStream zos, String rootpath, File source) throws IOException{ String filename = source.toString().substring(rootpath.length() + 1 ); if (source.isFile()){ zos.putNextEntry( new ZipEntry(filename)); FileInputStream fis = new FileInputStream(source); byte [] buffer = new byte [ 1024 ]; for ( int length; (length = fis.read(buffer)) > 0 ;){ zos.write(buffer, 0 , length); } fis.close(); zos.closeEntry(); } else if (source.isDirectory()){ zos.putNextEntry( new ZipEntry(filename + "/" )); zos.closeEntry(); File[] files = source.listFiles(); for (File file : files){ compress(zos, rootpath, file); } } } |