Here you can find the source of zipDir(String dir2zip, String zipFileName)
Parameter | Description |
---|---|
dir2zip | path of the directory to zip. |
zipFileName | name of the resulting zip file |
Parameter | Description |
---|---|
IOException | an exception |
public static void zipDir(String dir2zip, String zipFileName) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /** The default size to use for buffers when reading from InputStreams - 8192 bytes. */ public static final int CHUNK_SIZE = 8192; /**// w w w.j a va 2s . c om * Recursively zips a directory * @param dir2zip path of the directory to zip. * @param zipFileName name of the resulting zip file * @throws IOException * * @deprecated Do not use, it embeds the wrong paths into the zip file. Use ZipCreator instead. --jsb */ public static void zipDir(String dir2zip, String zipFileName) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName)); try { _zipDir(dir2zip, zos); } finally { zos.close(); } } public static void _zipDir(String dir2zip, ZipOutputStream zos) throws IOException { File zipDir = new File(dir2zip); String[] dirList = zipDir.list(); byte[] readBuffer = new byte[CHUNK_SIZE]; int bytesIn; //loop through dirList, and zip the files for (int i = 0; i < dirList.length; i++) { File f = new File(zipDir, dirList[i]); if (f.isDirectory()) { //if the File object is a directory, call this //function again to add its content recursively String filePath = f.getPath(); _zipDir(filePath, zos); continue; } FileInputStream fis = new FileInputStream(f); ZipEntry anEntry = new ZipEntry(f.getPath()); // FIX! shouldn't this be a relative path? zos.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); } } }