java解壓zip rar文件實例

jopen 11年前發布 | 23K 次閱讀 Java Java開發

 package com.tservice.mrn.common;

import java.io.*; import java.util.Enumeration;

import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.zip.*;

import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader;

public abstract class ZipUtils {

private static final int BUFFEREDSIZE = 1024;

/**

  • @SuppressWarnings({ "rawtypes", "resource" }) public static String
  • unzip(File zipFile, String unzipDir, String
  • zipFileName) throws IOException { ZipFile zf = new
  • ZipFile(zipFile); Enumeration enu = zf.entries();
  • String result = ""; while (enu.hasMoreElements()) {
  • ZipEntry entry = (ZipEntry) enu.nextElement(); String
  • name = entry.getName(); //
  • 如果解壓entry是目錄,直接生成目錄即可,不用寫入,如果是文件,要將文件寫入 String
  • pathParent = unzipDir + "/" + zipFileName; if (!(new
  • File(pathParent).exists())) new
  • File(pathParent).mkdirs(); String path = pathParent +
  • "/" + name; result = result + path + "<br/>
  • "; File file = new File(path); if
  • (entry.isDirectory()) { file.mkdir(); } else { //
  • 建議使用如下方式創建流和讀取字節,不然會有亂碼 InputStream is =
  • zf.getInputStream(entry); byte[] buf1 = new
  • byte[1024]; int len; if (!file.exists()) {
  • file.getParentFile().mkdirs(); file.createNewFile();
  • } OutputStream out = new FileOutputStream(file);
  • while ((len = is.read(buf1)) > 0) { String buf = new
  • String(buf1, 0, len); out.write(buf1, 0, len); } } }
  • result = "文件解壓成功,解壓文件:/n" + result; return result; } **/

    /**

  • 解壓zip或者rar包的內容到指定的目錄下,可以處理其文件夾下包含子文件夾的情況 *
  • @param zipFilename
  • 要解壓的zip或者rar包文件
  • @param outputDirectory
  • 解壓后存放的目錄 / public static void unzipZipRar(String zipFilename, String outputDirectory) throws Exception { File outFile = new File(outputDirectory); if (!outFile.exists()) { outFile.mkdirs(); }

    ZipFile zipFile = new ZipFile(zipFilename); @SuppressWarnings("rawtypes") Enumeration en = zipFile.getEntries(); ZipEntry zipEntry = null; while (en.hasMoreElements()) { zipEntry = (ZipEntry) en.nextElement(); if (zipEntry.isDirectory()) { // mkdir directory String dirName = zipEntry.getName(); // System.out.println("=dirName is:=" + dirName + "=end="); dirName = dirName.substring(0, dirName.length() - 1); File f = new File(outFile.getPath() + File.separator + dirName); f.mkdirs(); } else { // unzip file String strFilePath = outFile.getPath() + File.separator

    • zipEntry.getName(); File f = new File(strFilePath);

    // 判斷文件不存在的話,就創建該文件所在文件夾的目錄 if (!f.exists()) { String[] arrFolderName = zipEntry.getName().split("/"); String strRealFolder = ""; for (int i = 0; i < (arrFolderName.length - 1); i++) { strRealFolder += arrFolderName[i] + File.separator; } strRealFolder = outFile.getPath() + File.separator

    • strRealFolder; File tempDir = new File(strRealFolder); // 此處使用.mkdirs()方法,而不能用.mkdir() tempDir.mkdirs(); } // the codes remedified by can_do on 2010-07-02 =end= f.createNewFile(); InputStream in = zipFile.getInputStream(zipEntry); FileOutputStream out = new FileOutputStream(f); try { int c; byte[] by = new byte[BUFFEREDSIZE]; while ((c = in.read(by)) != -1) { out.write(by, 0, c); } // out.flush(); } catch (IOException e) { throw e; } finally { out.close(); in.close(); } } } }

    / /

  • 解壓zip格式壓縮包 對應的是ant.jar / private static void unzip(String sourceZip, String destDir) throws Exception { try { Project p = new Project(); Expand e = new Expand(); e.setProject(p); e.setSrc(new File(sourceZip)); e.setOverwrite(false); e.setDest(new File(destDir)); /

    • ant下的zip工具默認壓縮編碼為UTF-8編碼, 而winRAR軟件壓縮是用的windows默認的GBK或者GB2312編碼
    • 所以解壓縮時要制定編碼格式 */ e.setEncoding("gbk"); e.execute(); } catch (Exception e) { throw e; } }

    /**

  • 解壓rar格式壓縮包。
  • 對應的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又會用到commons-logging-1.1.1.jar */ private static void unrar(String sourceRar, String destDir) throws Exception { Archive a = null; FileOutputStream fos = null; try { a = new Archive(new File(sourceRar)); FileHeader fh = a.nextFileHeader(); while (fh != null) { if (!fh.isDirectory()) { // 1 根據不同的操作系統拿到相應的 destDirName 和 destFileName String compressFileName = fh.getFileNameString().trim(); String destFileName = ""; String destDirName = ""; // 非windows系統 if (File.separator.equals("/")) { destFileName = destDir

    + compressFileName.replaceAll("\\\\", "/");
    

    destDirName = destFileName.substring(0,

    destFileName.lastIndexOf("/"));
    

    // windows系統 } else { destFileName = destDir

    + compressFileName.replaceAll("/", "\\\\");
    

    destDirName = destFileName.substring(0,

    destFileName.lastIndexOf("\\"));
    

    } // 2創建文件夾 File dir = new File(destDirName); if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); } // 3解壓縮文件 fos = new FileOutputStream(new File(destFileName)); a.extractFile(fh, fos); fos.close(); fos = null; } fh = a.nextFileHeader(); } a.close(); a = null; } catch (Exception e) { throw e; } finally { if (fos != null) { try { fos.close(); fos = null; } catch (Exception e) { e.printStackTrace(); } } if (a != null) { try { a.close(); a = null; } catch (Exception e) { e.printStackTrace(); } } } }

    /**

  • 解壓縮 */ public static void deCompress(String sourceFile, String destDir) throws Exception { // 保證文件夾路徑最后是"/"或者"\" char lastChar = destDir.charAt(destDir.length() - 1); if (lastChar != '/' && lastChar != '\') { destDir += File.separator; } // 根據類型,進行相應的解壓縮 String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1); if (type.equals("zip")) { ZipUtils.unzip(sourceFile, destDir); } else if (type.equals("rar")) { ZipUtils.unrar(sourceFile, destDir); } else { throw new Exception("只支持zip和rar格式的壓縮包!"); } }

} </pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!