Here you can find the source of zip(File directory, File zipFile)
Parameter | Description |
---|---|
directory | the directory |
zipFile | the zip file |
public static void zip(File directory, File zipFile)
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**// w w w. j a v a2s . co m * Zip. * * @param directory the directory * @param zipFile the zip file */ public static void zip(File directory, File zipFile) { try { FileOutputStream os = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(os); zipDirectory(directory, directory, zos); zos.close(); os.close(); } catch (Exception e) { throw new RuntimeException(e); } } /** * Zip directory. * * @param root the root * @param directory the directory * @param zos the zos * @throws Exception the exception */ static void zipDirectory(File root, File directory, ZipOutputStream zos) throws Exception { for (File item : directory.listFiles()) { if (item.isDirectory()) { zipDirectory(root, item, zos); } else { byte[] readBuffer = new byte[2156]; int bytesIn; FileInputStream fis = new FileInputStream(item); String path = item.getAbsolutePath().substring(root.getAbsolutePath().length() + 1); ZipEntry anEntry = new ZipEntry(path); zos.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); } } } }