Here you can find the source of zipDirectory(File baseDirectory, File output)
Parameter | Description |
---|---|
baseDirectory | the input directory to be archived |
output | the ZIP archived directory |
public static void zipDirectory(File baseDirectory, File output)
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**/*from w ww . j ava 2s .c o m*/ * Create a ZIP archive of a directory. * The input directory may contains files and/or directories. * The algorithm used to browse the whole input base directory is not recursive. * @param baseDirectory the input directory to be archived * @param output the ZIP archived directory */ public static void zipDirectory(File baseDirectory, File output) { try { FileOutputStream fos = new FileOutputStream(output); ZipOutputStream zos = new ZipOutputStream(fos); Deque<File> directories = new ArrayDeque<File>(); if (baseDirectory.isDirectory()) { directories.add(baseDirectory); while (!directories.isEmpty()) { File directory = directories.poll(); for (File current : directory.listFiles()) { if (current.isDirectory()) { directories.add(current); } else if (current.isFile()) { ZipEntry ze = new ZipEntry(current.getAbsolutePath() .substring(baseDirectory.getAbsolutePath().length() + 1)); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(current); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } } } } zos.closeEntry(); zos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }