码迷,mamicode.com
首页 > 编程语言 > 详细

Java解压ZIP、RAR文件

时间:2016-05-12 21:10:52      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

解压ZIP:

maven地址:
<groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.9.7</version>
</dependency>
public static void unzipFile(String zipFileName) throws Exception {
    try {
    File f = new File(zipFileName);
    ZipFile zipFile = new ZipFile(zipFileName,"gbk");//windows要用gbk 否则文件名中文乱码
    if((!f.exists()) && (f.length() <= 0)) {
    throw new Exception("要解压的文件不存在!");
    }
    String strPath, gbkPath, strtemp;
    File tempFile = new File(f.getParent());
    strPath = tempFile.getAbsolutePath();
    Enumeration e = zipFile.getEntries();
    while(e.hasMoreElements()){
   ZipEntry zipEnt = (ZipEntry) e.nextElement();
    gbkPath=zipEnt.getName();
    if(zipEnt.isDirectory()){
    strtemp = strPath + "/" + gbkPath;
    File dir = new File(strtemp);
    dir.mkdirs();
    continue;
    } else {
    //读写文件
    InputStream is = zipFile.getInputStream(zipEnt);
    BufferedInputStream bis = new BufferedInputStream(is);
    gbkPath=zipEnt.getName();
    strtemp = strPath + "/" + gbkPath;
    //建目录
    String strsubdir = gbkPath;
    for(int i = 0; i < strsubdir.length(); i++) {
    if(strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
    String temp = strPath + "/" + strsubdir.substring(0, i);
    File subdir = new File(temp);
    if(!subdir.exists())
    subdir.mkdir();
    }
    }
    FileOutputStream fos = new FileOutputStream(strtemp);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int c;
    while((c = bis.read()) != -1) {
    bos.write((byte) c);
    }
    bos.close();
    fos.close();
    }
    }
    } catch(Exception e) {
    e.printStackTrace();
    throw e;
    }
    }

解压RAR:

<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactId>junrar</artifactId>
    <version>0.7</version>
</dependency>
/**
     * 解压rar格式的压缩文件到指定目录下
     * @param rarFileName 压缩文件
     * @param extPlace 解压目录
     * @throws Exception
     */
    public static void unrar(String rarFileName, String extPlace) throws Exception{
        try {
            File rar = new File(rarFileName);  
            File destinationFolder = new File(extPlace);  
            ExtractArchive extractArchive = new ExtractArchive();  
            extractArchive.extractArchive(rar, destinationFolder);  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }   

Java解压ZIP、RAR文件

标签:

原文地址:http://blog.csdn.net/flagang/article/details/51355043

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!