java实现对rar文件和zip文件的解压缩

java实现对rar文件和zip文件的解压缩

一.对zip文件的解压缩

1.1 使用ZIP4J实现

zip4j官方说明:

  • Create, Add, Extract, Update, Remove files from a Zip file
    针对ZIP压缩文件创建、添加、抽出、更新和移除文件
  • Read/Write password protected Zip files
    (读写有密码保护的Zip文件)
  • Supports AES 128/256 Encryption
    (支持AES 128/256算法加密)
  • Supports Standard Zip Encryption
    (支持标准Zip算法加密)
  • Supports Zip64 format
    (支持zip64格式)
  • Supports Store (No Compression) and Deflate compression method
    (支持Store(非压缩)Deflate压缩方法---不太明白)
  • Create or extract files from Split Zip files (Ex: z01, z02,...zip)
    (针对分块zip文件创建和抽出文件)
  • Supports Unicode file names
    (支持Unicode编码文件名)
  • Progress Monitor
    (进度监控)

   从以上的主要特性可以看出,zip4j的功能是非常强大的,完全可以利用其写个类似于好压的zip文件管理软件。

使用注意点:

zip4j默认采用UTF-8编码,所以它支持中文,同时也支持密码,而且支持多种压缩算法,可以说功能强大,但使用起来却非常简单,当然,如果需求比较复杂,那就得好好去研究了。如果你仅仅是简单地解压一个zip压缩文件,那么只需要简单地几步即可:

1. maven工程中加入依赖:

 

   <dependency>

       <groupId>net.lingala.zip4jgroupId>

       <artifactId>zip4jartifactId>

       <version>1.3.2version>

   dependency>

2.新建类UnZip.java:

package com.test;

 

import java.io.File; 

import java.io.IOException; 

import java.util.ArrayList;

import java.util.List;

import net.lingala.zip4j.core.ZipFile;

import net.lingala.zip4j.exception.ZipException;

import net.lingala.zip4j.model.FileHeader;

 

 

public classUnZip {

  

   public static void main(String[] args) throws IOException{

     

      Stringsource="C:\\ygcl.zip";

      Stringdest="C:\\ygcl";

      Stringpassword="password";

      try {

         FilezipFile=new File(source);

            ZipFile zFile = new ZipFile(zipFile);  // 首先创建ZipFile指向磁盘上的.zip文件   

            zFile.setFileNameCharset("GBK");

              File destDir = new File(dest);     // 解压目录   

              if (zFile.isEncrypted()) {   

                  zFile.setPassword(password.toCharArray());  // 设置密码   

              }

              zFile.extractAll(dest);      // 将文件抽出到解压目录(解压)   

     

             List headerList = zFile.getFileHeaders()

              List extractedFileList= newArrayList(); 

              for(FileHeader fileHeader : headerList) { 

                  if (!fileHeader.isDirectory()) { 

                      extractedFileList.add(new File(destDir,fileHeader.getFileName())); 

                  } 

              } 

              File [] extractedFiles = new File[extractedFileList.size()]; 

             extractedFileList.toArray(extractedFiles); 

             

              for(File f:extractedFileList){

                System.out.println(f.getAbsolutePath()+"....");

              }

      }catch(ZipException e) {

         // TODO: handle exception

      } 

}

}

1.2 使用ant依赖实现

步骤:

1.maven工程中引入依赖:

<dependency>

            <groupId>antgroupId>

            <artifactId>antartifactId>

            <version>1.6.5version>

dependency>

2. 新建UnZip.java:

packagecom.test;

 

importjava.io.File;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importjava.util.Enumeration;

importorg.apache.tools.zip.ZipEntry;

importorg.apache.tools.zip.ZipFile;

 

publicclass UnZip {

 

         public static void main(String[] args)throws Exception {

                  

                   unZipFiles(newFile("C:\\ygcl.zip"),"C:\\ygcl\\");

         }

        

         public static void unZipFiles(FilezipFile,String descDir)throws IOException{ 

 

           File pathFile = new File(descDir); 

       if(!pathFile.exists()){ 

           pathFile.mkdirs(); 

       } 

       ZipFile zip = newZipFile(zipFile,"GBK"); 

       for(Enumeration entries =zip.getEntries();entries.hasMoreElements();){ 

           ZipEntry entry =(ZipEntry)entries.nextElement(); 

           String zipEntryName = entry.getName(); 

           InputStream in =zip.getInputStream(entry); 

           String outPath =(descDir+zipEntryName).replaceAll("\\*", "/");; 

           //判断路径是否存在,不存在则创建文件路径 

           File file = newFile(outPath.substring(0, outPath.lastIndexOf('/'))); 

           if(!file.exists()){ 

               file.mkdirs(); 

           } 

           //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压 

           if(newFile(outPath).isDirectory()){ 

               continue; 

           } 

           //输出文件路径信息 

           System.out.println(outPath); 

            

           OutputStream out = newFileOutputStream(outPath); 

           byte[] buf1 = new byte[1024]; 

           int len; 

          while((len=in.read(buf1))>0){ 

               out.write(buf1,0,len); 

           } 

           in.close(); 

           out.close(); 

           } 

      System.out.println("******************解压完毕********************"); 

   } 

}

二.对rar文件的解压缩

2.1 使用junrar依赖实现

1.maven工程中加入依赖:

  <dependency>

            <groupId>com.github.junrargroupId>

            <artifactId>junrarartifactId>

            <version>0.7version>

       dependency>

2.新建UnRar.java

package com.test;

 

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File; 

import java.io.FileInputStream;

import java.io.FileOutputStream; 

 

 

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.charset.Charset;

import java.util.Enumeration;

import java.util.LinkedList;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

 

 

import com.github.junrar.Archive;

import com.github.junrar.rarfile.FileHeader;

 

 

 /*

   * maven项目,添加依赖:

  *  

           com.github.junrar

            junrar

            0.7

       

  */

public classUnRar{ 

  

   public static void main(String[] args) throws Exception{

      UnRar2u=new UnRar2();

      u.unrar("D:\\存放资料的压缩包\\员工材料.rar","D:\\存放资料的非压缩包\\");

   }

  

   public  void unrar(String srcRarPath,String dstDirectoryPath)throwsException { 

        if (!srcRarPath.toLowerCase().endsWith(".rar")) {

             System.out.println("rar文件!");

              return;

          }

          File dstDiretory = new File(dstDirectoryPath);

          if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹

              dstDiretory.mkdirs();

          }

          File fol=null,out=null;

          Archive a = null;

          try {

              a = new Archive(new File(srcRarPath));

              if (a != null){

                  a.getMainHeader().print(); // 打印文件信息.

                  FileHeader fh = a.nextFileHeader();

                  while (fh != null){

                      if (fh.isDirectory()) { // 文件夹

                      // 如果是中文路径,调用getFileNameW()方法,否则调用getFileNameString()方法,还可以使用if(fh.isUnicode())

                      if(existZH(fh.getFileNameW())){

                         fol = new File(dstDirectoryPath + File.separator

                                      + fh.getFileNameW());

                      }else{

                          fol = new File(dstDirectoryPath + File.separator

                                      + fh.getFileNameString());

                      }

                       

                          fol.mkdirs();

                      } else { // 文件

                      if(existZH(fh.getFileNameW())){

                           out = new File(dstDirectoryPath + File.separator

                                      + fh.getFileNameW().trim());

                      }else{

                          out = new File(dstDirectoryPath + File.separator

                                      + fh.getFileNameString().trim());

                      }

                       

                          //System.out.println(out.getAbsolutePath());

                          try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.

                              if (!out.exists()) {

                                  if (!out.getParentFile().exists()){// 相对路径可能多级,可能需要创建父目录.

                                      out.getParentFile().mkdirs();

                                  }

                                  out.createNewFile();

                              }

                              FileOutputStream os = new FileOutputStream(out);

                              a.extractFile(fh, os);

                              os.close();

                          } catch (Exception ex) {

                              ex.printStackTrace();

                          }

                      }

                      fh = a.nextFileHeader();

                  }

                 a.close();

              }

          } catch (Exception e) {

              e.printStackTrace();

          }

     }

   

   /*

     * 判断是否是中文

     */

   publicstaticbooleanexistZH(String str){ 

        String regEx = "[\\u4e00-\\u9fa5]"

        Pattern p = Pattern.compile(regEx); 

        Matcher m = p.matcher(str); 

        while (m.find()) { 

            return true

        } 

        return false

   }

   

}

 

2.2 使用java.unrar-0.3.jar和commons-logging.jar实现

1.项目引入java.unrar-0.3.jar和commons-logging.jar

2.新建UnRar类:

package a;

 

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File; 

import java.io.FileInputStream;

import java.io.FileOutputStream; 

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.charset.Charset;

import java.util.Enumeration;

import java.util.LinkedList;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import de.innosystec.unrar.Archive; 

import de.innosystec.unrar.rarfile.FileHeader; 

  /*

   * 需要引入java.unrar-0.3.jar和commons-logging.jar

   */

public class UnRar{ 

  

   publicstatic void main(String[] args) throws Exception{

      UnRar2u=new UnRar2();

      u.unrar(newFile("D:\\存放资料的压缩包\\员工材料.rar"),newFile("D:\\存放资料的非压缩包\\"));

   }

  

   public  void unrar(File sourceRar,File destDir) throws Exception { 

       Archive archive = null; 

       FileOutputStream fos = null; 

       System.out.println("Starting..."); 

       try { 

           archive = new Archive(sourceRar); 

           FileHeader fh = archive.nextFileHeader(); 

           int count = 0; 

           File destFileName = null; 

           while (fh != null) { 

              

               

               

               String compressFileName=""; 

               

               System.out.println(fh.isUnicode());

               // 判断文件路径是否有中文

               if(existZH(fh.getFileNameW())){

                  System.out.println((++count) + ") "+ fh.getFileNameW());

                compressFileName =fh.getFileNameW().trim(); 

               }else{ 

                 System.out.println((++count) + ") "+ fh.getFileNameString());

                compressFileName =fh.getFileNameString().trim();   

               } 

 

               destFileName = new File(destDir.getAbsolutePath() + "/" +compressFileName); 

               if (fh.isDirectory()) { 

                    if (!destFileName.exists()){ 

                       destFileName.mkdirs(); 

                    } 

                    fh =archive.nextFileHeader(); 

                    continue; 

               }  

               if (!destFileName.getParentFile().exists()) { 

                   destFileName.getParentFile().mkdirs(); 

                } 

               fos = new FileOutputStream(destFileName); 

               archive.extractFile(fh, fos); 

               fos.close(); 

               fos = null; 

               fh = archive.nextFileHeader(); 

           } 

 

            archive.close(); 

           archive = null; 

           System.out.println("Finished !"); 

        }catch (Exception e) { 

           throw e; 

        }finally { 

           if (fos != null) { 

               try { 

                    fos.close(); 

                    fos = null; 

               } catch (Exception e) { 

                    //ignore 

               } 

           } 

           if (archive != null) { 

               try { 

                    archive.close();  

                    archive = null; 

               } catch (Exception e) { 

                    //ignore 

               } 

           } 

       } 

    }

    // 判断路径是否带中文

    publicstatic boolean existZH(String str) { 

       String regEx = "[\\u4e00-\\u9fa5]"; 

       Pattern p = Pattern.compile(regEx); 

       Matcher m = p.matcher(str); 

       while (m.find()) { 

           return true; 

       } 

       return false; 

    }

   

}

 

 

 

 

 

 

    

 

 

你可能感兴趣的:(java)