zip、unzip工具类

用于进行zip文件解压和将文件打成zip包的工具,支持对嵌套文件夹的压缩,更多内容请访问我的 blog
/********************************************************************
 * 项目名称    :ConfigCheck   <p>
 * 包名称      :com.rochoc.cck.util <p>
 * 文件名称    :ZipTool   <p>
 * 编写者     :luoc    <p>
 * 编写日期    :2005-10-3    <p>
 * 程序功能(类)描述 : 对文件进行打包或对zip包进行解包<p>
 * 
 * 程序变更日期   :
 * 变更作者    :
 * 变更说明    :
 ********************************************************************/
package com.rochoc.cck.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 类名:ZipTool  <p>
 * 类描述:对文件进行打包或对zip包进行解包<p>
 * 编写者 :luoc<p>
 * 编写日期 :2005-10-3<p>
 * 主要public成员变量:<p>
 * 主要public方法:   <p>
 **/

public class ZipTool
{
    /**
    * 方法名称:zip<p>
    * 方法功能:对指定路径srcPath进行打包,打成zip包放入zipPath中<p>
    * 参数说明:@param zipPath 打包后的结果包
    * 参数说明:@param srcPath 需要打包的文件夹
    * 参数说明:@throws Exception <p>
    * 返回:void <p>
    * 作者:luoc
    * 日期:2005-10-3
    **/
    public static void zip(String zipPath,String srcPath)
    throws Exception
    {
        /** 打包后的zip文件*/
        FileOutputStream output = null;
        ZipOutputStream zipOutput = null;
        output = new FileOutputStream(zipPath);
        zipOutput =new ZipOutputStream((java.io.OutputStream) output);
        
        zipEntry(zipOutput,srcPath,srcPath);
        /** 保存zip文件*/
        zipOutput.close();        
    }
    
    /**
    * 方法名称:zipEntry<p>
    * 方法功能:将一文件放到zipEntry中<p>
    * 参数说明:@param zipOs zip输出流
    * 参数说明:@param initPath 需打包文件初始目录
    * 参数说明:@param filePath 当前打包的文件
    * 参数说明:@throws Exception <p>
    * 返回:void <p>
    * 作者:luoc
    * 日期:2005-10-3
    **/
    private static void zipEntry(ZipOutputStream zipOs,String initPath,String filePath)
    throws Exception
    {
        String entryName = filePath;
        File f = new File(filePath);
        if(f.isDirectory())//目录
        {
            String[] files = f.list();
            for(int i=0;i<files.length;i++)
                zipEntry(zipOs,initPath,filePath+File.separator+files[i]);
            return;
        }
        String chPh = initPath.substring(initPath.lastIndexOf(File.separatorChar)+1);//起始文件夹
        int idx = filePath.lastIndexOf(chPh);                
        if (idx != -1) {
            entryName = filePath.substring(idx);            
        }
        
        ZipEntry entry;
        entry = new ZipEntry(entryName);
        File ff = new File(filePath);
        
        entry.setSize(ff.length());
        entry.setTime(ff.lastModified());
        
        /** 设置CRC校验 */
        entry.setCrc(0);
        CRC32 crc = new CRC32();
        crc.reset();
        
        zipOs.putNextEntry(entry);
        
        FileInputStream input = new FileInputStream(filePath);
        
        int len = 0;
        byte[] buffer = new byte[2048];
        int bufferLen = 2048;
        
        while ((len = input.read(buffer, 0, bufferLen)) != -1) {
            zipOs.write(buffer, 0, len);
            crc.update(buffer, 0, len);
        }
        
        entry.setCrc(crc.getValue());
    }
    
    /**
    * 方法名称:unzip<p>
    * 方法功能:对指定的zip文件进行解包<p>
    * 参数说明:@param desPath 解包到文件夹
    * 参数说明:@param args 要进行解包的zip文件<p>
    * 返回:void <p>
    * 作者:luoc
    * 日期:2005-10-3
    **/
    public static void unzip(String desPath,String args)
    {        
        if (!(new File(args)).exists())
        {
            System.out.println("can't open " + args);
            return;
        }
        try
        {
            ZipFile archive = new ZipFile(args);
            
            // do our own buffering; reuse the same buffer.
            byte[] buffer = new byte[16384];
            
            for (Enumeration e = archive.entries(); e.hasMoreElements();)
            {
                // get the next entry in the archive
                ZipEntry entry = (ZipEntry) e.nextElement();
                
                String filename = desPath+File.separatorChar+entry.getName();
                filename = filename.replace('/', File.separatorChar);
                File destFile = new File(filename);
                if(entry.isDirectory())
                {
                    destFile.mkdir();
                    continue;
                }
                if (destFile.exists())
                {
                    System.out.println(
                            "..skipping "
                            + filename
                            + " (overwrite not implemented).");
                }
                else
                {
                    System.out.println("..writing " + filename);
                    
                    // create the destination path, if needed
                    String parent = destFile.getParent();                    
                    if (parent != null)
                    {
                        File parentFile = new File(parent);
                        if (!parentFile.exists())
                        {
                            // create the chain of subdirs to the file
                            parentFile.mkdirs();
                        }
                    }
                    
                    // get a stream of the archive entry's bytes
                    InputStream in = archive.getInputStream(entry);
                    
                    // open a stream to the destination file
                    OutputStream out = new FileOutputStream(filename);
                    
                    // repeat reading into buffer and writing buffer to file,
                    // until done.  count will always be # bytes read, until
                    // EOF when it is -1.
                    int count;
                    while ((count = in.read(buffer)) != -1)
                        out.write(buffer, 0, count);
                    
                    in.close();
                    out.close();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
    * 方法名称:unzip<p>
    * 方法功能:返回zip包中的文件            <p>
    * 参数说明:@param desPath zip文件路径
    * 参数说明:@return
    * 参数说明:@throws IOException
    * 参数说明:@throws FileNotFoundException <p>
    * 返回:ZipEntry[] <p>
    * 作者:luoc
    * 日期:2005-10-3
    **/
    public static ZipEntryObject[] unzip(String desPath)
    throws IOException,FileNotFoundException
    {
        if (!(new File(desPath)).exists())
        {
            throw (new FileNotFoundException("Zip文件【"+desPath+"】不存在"));
        }         
        ZipFile archive = new ZipFile(desPath);
        ZipEntryObject entrys []= new ZipEntryObject[archive.size()];
        int idx = 0;
        for (Enumeration e = archive.entries(); e.hasMoreElements();)
        {
            // get the next entry in the archive
            ZipEntry entry = (ZipEntry) e.nextElement();
            entrys[idx] = new ZipEntryObject(entry,archive.getInputStream(entry));            
            idx++;
        }
        return entrys;
    }
}

ZipEntryObject类

 /********************************************************************
 *  ============================================= 
 *  The Rochoc Software License v1.0 content. 
 *  Copyright (c) Rochoc Group, 2005-2006
 *  =============================================  
 * 项目名称    :ConfigCheck<p>
 * 包名称      :com.rochoc.cck.util<p>
 * 文件名称    :ZipEntryObject.java<p>
 * 编写者     :Administrator<p>
 * 编写日期    :2005-10-4<p>
 * 程序功能(类)描述     :用于保存从zip包中解释得到的entry,包括InputStream
 * <p> 
 * 程序变更日期   :
 * 变更作者    :
 * 变更说明    :
 ********************************************************************/
package com.rochoc.cck.util;

import java.io.InputStream;
import java.util.zip.ZipEntry;

/**
 * 类名:ZipEntryObject<p>
 * 类描述:用于保存从zip包中解释得到的entry,包括InputStream
 * <p>
 * 编写者 :Administrator<p>
 * 编写日期 :2005-3-19<p>
 * 主要public成员变量:<p>
 * 主要public方法:<p>
 **/
public class ZipEntryObject 
{
    /** 全局变量 */
    /** Entry */
    private ZipEntry entry = null;
    
    /** InputStream */
    private InputStream inputStream = null;
    
    public ZipEntryObject(ZipEntry entry,InputStream is)
    {
        this.entry = entry;
        this.inputStream = is;
    }
    
    
    /**
     * @return 返回 entry。
     */
    public ZipEntry getEntry() {
        return entry;
    }
    /**
     * @param entry 要设置的 entry。
     */
    public void setEntry(ZipEntry entry) {
        this.entry = entry;
    }
    /**
     * @return 返回 inputStream。
     */
    public InputStream getInputStream() {
        return inputStream;
    }
    /**
     * @param inputStream 要设置的 inputStream。
     */
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的解压 zip 文件的工具类的实现(使用 Java 语言): ``` import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class UnzipTool { public static void unzip(String zipFilePath, String destDir) throws IOException { File destFile = new File(destDir); // 如果目标文件夹不存在,则创建 if (!destFile.exists()) { destFile.mkdir(); } ZipFile zipFile = new ZipFile(zipFilePath); // 获取 zip 文件中所有的条目 Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); InputStream in = zipFile.getInputStream(entry); String outPath = destDir + File.separator + entryName; // 如果是文件夹,则创建文件夹 if (entry.isDirectory()) { File file = new File(outPath); file.mkdir(); } else { // 如果是文件,则写入文件 FileOutputStream out = new FileOutputStream(outPath); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } zipFile.close(); } } ``` 使用方法: 1. 调用 `UnzipTool.unzip(zipFilePath, destDir);` 进行解压,其中 `zipFilePath` 是要解压的 zip 文件路径,`destDir` 是解压后的文件夹路径 2. 解压完成后,zip 文件中的所有文件和文件夹都会被解压到 `destDir` 文件夹中 注意:以上代码只是一个简单的解压 zip 文件的实现,还有很多细节需要考虑,例如文件名编码、文件覆盖、异常处理等。如果需要在实际项目中使用解压工具类,建议使用成熟的第三方库,例如 Apache Commons Compress。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值