java zip 解压缩

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class ZipUtil {  
    Logger logger = Logger.getLogger(ZipUtil.class.getSimpleName());  
 
    /** Constants for mode listing or mode extracting. */ 
    public static final int LIST = 0, EXTRACT = 1;  
 
    /** Whether we are extracting or just printing TOC */ 
    protected int mode = LIST;  
 
    /** The ZipFile that is used to read an archive */ 
    protected ZipFile zippy;  
 
    /** The buffer for reading/writing the ZipFile data */ 
    protected byte[] b;  
 
    private String unzipFileTargetLocation;  
 
    public ZipUtil() {  
        b = new byte[8092];  
    }  
 
    /** Set the Mode (list, extract). */ 
    public void setMode(int m) {  
        if (m == LIST || m == EXTRACT)  
            mode = m;  
    }  
 
    /** Cache of paths we've mkdir()ed. */ 
    protected SortedSet dirsMade;  
 
    /** 
     * For a given Zip file, process each entry. 
     *  
     * @param fileName 
     *            unzip file name 
     * @param unZipTarget 
     *            location for unzipped file 
     */ 
    public void unZip(String fileName, String unZipTarget) {  
        this.unzipFileTargetLocation = unZipTarget;  
        dirsMade = new TreeSet();  
        try {  
            zippy = new ZipFile(fileName);  
            Enumeration all = zippy.entries();  
            while (all.hasMoreElements()) {  
                getFile((ZipEntry) all.nextElement());  
            }  
        } catch (IOException err) {  
            //logger.error("IO Error: " + err);  
            return;  
        }  
    }  
 
    protected boolean warnedMkDir = false;  
 
    /** 
     * Process one file from the zip, given its name. Either print the name, or 
     * create the file on disk. 
     */ 
    protected void getFile(ZipEntry e) throws IOException {  
        String zipName = e.getName();  
        switch (mode) {  
        case EXTRACT:  
            if (zipName.startsWith("/")) {  
                if (!warnedMkDir)  
                    System.out.println("Ignoring absolute paths");  
                warnedMkDir = true;  
                zipName = zipName.substring(1);  
            }  
            // if a directory, just return. We mkdir for every file,  
            // since some widely-used Zip creators don't put out  
            // any directory entries, or put them in the wrong place.  
            if (zipName.endsWith("/")) {  
                return;  
            }  
            // Else must be a file; open the file for output  
            // Get the directory part.  
            int ix = zipName.lastIndexOf('/');  
            if (ix > 0) {  
                String dirName = zipName.substring(0, ix);  
                String fileName=zipName.substring(ix+1,zipName.length());  
                zipName=fileName;  
                  
            }  
            //logger.debug("Creating " + zipName);  
            String targetFile = this.unzipFileTargetLocation;  
            File file=new File(targetFile);  
            if(!file.exists())  
                file.createNewFile();  
            FileOutputStream os = new FileOutputStream(targetFile);  
            InputStream is = zippy.getInputStream(e);  
            int n = 0;  
            while ((n = is.read(b)) > 0)  
                os.write(b, 0, n);  
            is.close();  
            os.close();  
            break;  
        case LIST:  
            // Not extracting, just list  
            if (e.isDirectory()) {  
                logger.info("Directory " + zipName);  
            } else {  
                logger.info("File " + zipName);  
            }  
            break;  
        default:  
            throw new IllegalStateException("mode value (" + mode + ") bad");  
        }  
    }  
 
    /** 
     * unzip zip file with 
     *  
     * @param unZipFile,and 
     *            save unzipped file to 
     * @param saveFilePath 
     * @param unZipFile 
     *            full file path,like 'd:/temp/test.zip' 
     * @param saveFilePath 
     *            full file path,like 'd:/temp/test.kml' 
     * @return 
     */ 
    public static boolean unzip(String unZipFile, String saveFilePath) {  
        boolean succeed = true;  
        ZipInputStream zin = null;  
        ZipEntry entry;  
        try {  
            // zip file path  
            File olddirec = new File(unZipFile);  
            zin = new ZipInputStream(new FileInputStream(unZipFile));  
            // iterate ZipEntry in zip  
            while ((entry = zin.getNextEntry()) != null) {  
                // if folder,create it  
                if (entry.isDirectory()) {  
                    File directory = new File(olddirec.getParent(), entry  
                            .getName());  
                    if (!directory.exists()) {  
                        if (!directory.mkdirs()) {  
                            System.out.println("Create foler in " 
                                    + directory.getAbsoluteFile() + " failed");  
                        }  
                    }  
                    zin.closeEntry();  
                }  
                // if file,unzip it  
                if (!entry.isDirectory()) {  
                    File myFile = new File(saveFilePath);  
                    FileOutputStream fout = new FileOutputStream(myFile);  
                    DataOutputStream dout = new DataOutputStream(fout);  
                    byte[] b = new byte[1024];  
                    int len = 0;  
                    while ((len = zin.read(b)) != -1) {  
                        dout.write(b, 0, len);  
                    }  
                    dout.close();  
                    fout.close();  
                    zin.closeEntry();  
                }  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            succeed = false;  
            System.out.println(e);  
        } finally {  
            if (null != zin) {  
                try {  
                    zin.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        if (succeed)  
            System.out.println("File unzipped successfully!");  
        else 
            System.out.println("File unzipped with failure!");  
        return succeed;  
    }  
 
    /** 
     * @param args 
     */ 
    public static void main(String[] args) {  
        String unzipfile = "G://test//dmhy.zip"; // 解压缩的文件名  
        String saveTo = "G://test//dmhy.xml";  
        boolean success = ZipUtil.unzip(unzipfile, saveTo);  
        if (success)  
            System.out.println("File ");  
    } 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值