Here you can find the source of zipDirectory(File inputDirectory, File zipFile)
Parameter | Description |
---|---|
inputDirectory | The input directory. |
zipFile | The zip file. |
Parameter | Description |
---|---|
IOException | an exception |
public static void zipDirectory(File inputDirectory, File zipFile) throws IOException
//package com.java2s; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**//from w w w . ja v a 2 s . co m * Zip compresses a directory. * * @param inputDirectory The input directory. * @param zipFile The zip file. * @throws IOException */ public static void zipDirectory(File inputDirectory, File zipFile) throws IOException { FileOutputStream dest = new FileOutputStream(zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); // gather files and zip them constructZip(inputDirectory, out, ""); out.close(); } private static void constructZip(File file, ZipOutputStream out, String dir) throws IOException { BufferedInputStream origin = null; int BUFFER = 2048; byte data[] = new byte[BUFFER]; File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { constructZip(files[i], out, dir + files[i].getName() + File.separator); continue; } // read file FileInputStream fi = new FileInputStream(files[i]); origin = new BufferedInputStream(fi, BUFFER); // create zip entry ZipEntry entry = new ZipEntry(dir + files[i].getName()); // add entries to ZIP file out.putNextEntry(entry); // write data int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } // close origin.close(); } } }