通过apache开源包ant-1.9.4.jar(下载)的工具包中zip提供ZipOutputStream、ZipEntry类来实现对文件或文件夹目录的压缩打包,代码工具类ZipUtils如下
package xwood.tools;@b@@b@import java.io.BufferedInputStream;@b@import java.io.BufferedOutputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.InputStream;@b@import java.io.OutputStream;@b@@b@import org.apache.tools.zip.ZipEntry;@b@import org.apache.tools.zip.ZipOutputStream;@b@@b@public class ZipUtils {@b@ /**@b@ * 压缩文件@b@ * @param sourceDir@b@ * 原文件目录@b@ * @param zipFile@b@ * 压缩后的文件名称@b@ * @throws Exception@b@ */@b@ public static void doZip(String sourceDir, File zipFile) throws Exception{@b@ OutputStream os= new FileOutputStream(zipFile);@b@ BufferedOutputStream bos = new BufferedOutputStream(os);@b@ ZipOutputStream zos = new ZipOutputStream(bos);@b@ File file = new File(sourceDir);@b@ String basePath = null;@b@ if (file.isDirectory()) {@b@ basePath = file.getPath();@b@ } else {@b@ basePath = file.getParent();@b@ }@b@ zipFile(file, basePath, zos);@b@ zos.closeEntry();@b@ zos.close();@b@ }@b@@b@ /**@b@ * 压缩文件@b@ * @param source@b@ * @param basePath@b@ * @param zos@b@ * @throws Exception@b@ */@b@ private static void zipFile(File source, String basePath,ZipOutputStream zos) throws Exception {@b@ File[] files = new File[0];@b@ if (source.isDirectory()) {@b@ files = source.listFiles();@b@ } else {@b@ files = new File[1];@b@ files[0] = source;@b@ }@b@ String pathName;@b@ byte[] buf = new byte[1024];@b@ int length = 0;@b@ for (File file : files) {@b@ if (file.isDirectory()) {@b@ pathName = file.getPath().substring(basePath.length() + 1)+ "/";@b@ zos.putNextEntry(new ZipEntry(pathName));@b@ zipFile(file, basePath, zos);@b@ } else {@b@ pathName = file.getPath().substring(basePath.length() + 1);@b@ InputStream is = new FileInputStream(file);@b@ BufferedInputStream bis = new BufferedInputStream(is);@b@ zos.putNextEntry(new ZipEntry(pathName));@b@ while ((length = bis.read(buf)) > 0) {@b@ zos.write(buf, 0, length);@b@ }@b@ is.close();@b@ }@b@ }@b@ }@b@ @b@ public static void main(String[] args) throws Exception{@b@ ZipUtils.doZip("C:/NJ/bak/js",new File("C:/NJ/bak/js_bak.zip"));@b@ }@b@@b@}
运行结果如下图所示