ZIP解壓縮工具類
阿新 • • 發佈:2018-04-25
ant des pre -- void jar lse sys directory
import java.io.File; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.types.FileSet; /** * ZIP解壓縮工具類 */ public class Zipper { // ZIP解壓縮時 public final static String encoding = "GBK"; /*** 壓縮文件或文件夾 * ------------------------------------ * @param srcPathname 需要被壓縮的文件或文件夾路徑 * @param zipFilepath 將要生成的ZIP文件路徑 */ public static void zip(String srcPathname, String zipFilepath) throws Exception { System.out.println(String.format("start compress ( %s ).", srcPathname));// 檢查文件是否存在 File file = new File(srcPathname); if (!file.exists()) { throw new RuntimeException(String.format("source file or directory ( %s ) does not exist.", srcPathname)); } // 創建項目 Project proj = new Project(); // 文件設置 FileSet fileSet = newFileSet(); fileSet.setProject(proj); if (file.isDirectory()) { // 如果是目錄 fileSet.setDir(file); } else { // 如果是單個文件 fileSet.setFile(file); } // 壓縮文件保存到目標地址 Zip zip = new Zip(); zip.setProject(proj); zip.setDestFile(new File(zipFilepath)); zip.addFileset(fileSet); zip.setEncoding(encoding); zip.execute(); System.out.println(String.format("compress successed of ( %s ). zip file is ( %s )", srcPathname, zipFilepath)); } /** * 解壓縮文件或文件夾 * ------------------------------------ * @param zipFilepath 需要被解壓的ZIP文件路徑 * @param destDir 將要被解壓到的目標文件夾 */ public static void unzip(String zipFilepath, String destDir) throws Exception { System.out.println(String.format("start uncompress ( %s ).", zipFilepath)); // 判斷要解壓的ZIP包是否存在 File file = new File(zipFilepath); if (!file.exists()) { throw new RuntimeException(String.format("zip file ( %s ) does not exist.", zipFilepath)); } // 創建項目 Project proj = new Project(); // 解壓設置 Expand expand = new Expand(); expand.setProject(proj); expand.setTaskType("unzip"); expand.setTaskName("unzip"); expand.setEncoding(encoding); expand.setSrc(new File(zipFilepath)); expand.setDest(new File(destDir)); // 執行解壓 expand.execute(); System.out.println(String.format("uncompress successed of ( %s ).", zipFilepath)); } /** * 測試解壓縮方法 */ public static void main(String[] args) { /*try { String srcPathname = "D:\\test\\test"; String zipFilepath = "D:\\test\\test.zip"; Zipper.zip(srcPathname, zipFilepath); } catch (Exception e) { e.printStackTrace(); }*/ try { String zipFilepath = "D:\\test\\test.zip"; String destDir = "D:\\test\\upzip"; Zipper.unzip(zipFilepath, destDir); } catch (Exception e) { e.printStackTrace(); } } }
依賴jar
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.7</version>
</dependency>
ZIP解壓縮工具類