压缩解压zip文件包
import java.io.*;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.tools.zip.*;import java.util.Enumeration;
?
public class AntZip{ // 日志对象 private static Log logger = LogFactory.getLog(AntZip.class); /** * <压缩指定的文件夹> * <该方法只能压缩文件夹> * @param zipDirectory 需要压缩的文件夹全路径 * @param destFile 压缩后的文件存放路径,包括压缩后的文件名 * @see [类、类#方法、类#成员] */ public static void doZip(String zipDirectory, String destFile) { File zipDir = new File(zipDirectory); try { ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destFile))); handleDir(zipDir, zipOut); zipOut.close(); } catch (IOException e) { logger.error(Global.LOG_EXCEPTION_NAME, e); } } /** * <由doZip调用,递归完成目录文件读取> * <功能详细描述> * @param dir 文件 * @param zipOut 压缩输出对象 * @throws IOException * @see [类、类#方法、类#成员] */ private static void handleDir(File dir, ZipOutputStream zipOut) throws IOException { FileInputStream fileIn; File[] files; files = dir.listFiles(); if (files.length == 0) { //如果目录为空,则单独创建之. //ZipEntry的isDirectory()方法中,目录以"/"结尾. zipOut.putNextEntry(new ZipEntry(dir.toString() + "/")); zipOut.closeEntry(); } else { //如果目录不为空,则分别处理目录和文件. for (File fileName : files) { if (fileName.isDirectory()) { handleDir(fileName, zipOut); } else { fileIn = new FileInputStream(fileName); String path = fileName.getPath().substring(fileName.getPath().lastIndexOf("\") + 1); zipOut.putNextEntry(new ZipEntry(path)); byte[] buf = new byte[1024]; int readedBytes = 0; while ((readedBytes = fileIn.read(buf)) > 0) { zipOut.write(buf, 0, readedBytes); } fileIn.close(); zipOut.closeEntry(); } } } } /** * <解压指定zip文件> * <解压指定zip压缩包到指定目录> * @param unZipfileName 压缩包 * @param destDir 目标目录 * @see [类、类#方法、类#成员] */ @SuppressWarnings("rawtypes") public static void unZip(String unZipfileName, String destDir) { //unZipfileName需要解压的zip文件名 FileOutputStream fileOut; File file; InputStream inputStream; try { ZipFile zipFile = new ZipFile(unZipfileName); for (Enumeration entries = zipFile.getEntries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry)entries.nextElement(); file = new File(entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { //如果指定文件的目录不存在,则创建之. String path = destDir + "/" + file.getParent(); File parent = new File(path); if (!parent.exists()) { parent.mkdirs(); } inputStream = zipFile.getInputStream(entry); fileOut = new FileOutputStream(destDir + "/" + file); byte[] buf = new byte[1024]; int readedBytes = 0; while ((readedBytes = inputStream.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); inputStream.close(); } } zipFile.close(); } catch (IOException e) { logger.error(Global.LOG_EXCEPTION_NAME, e); } }}?