import org.apache.log4j.LogManager; import org.apache.log4j.Logger; 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; import java.io.File; public class ZipUtil { private final Project DEFAULT_PROJECT = new Project(); private Logger log= LogManager.getLogger(ZipUtil.class.getName()); public void unZip(String orginFilePath, String destFilePath) { try { File orgin=new File(orginFilePath); File dest=new File(destFilePath); Expand expand = new Expand(); expand.setProject(DEFAULT_PROJECT); expand.setSrc(orgin); expand.setDest(dest); expand.execute(); } catch (Exception e) { log.error("解压文件时,出现异常 :",e); } } public void zip(String orginFilePath, String destFilePath) { try { File orgin=new File(orginFilePath); File dest=new File(destFilePath); Zip zip = new Zip(); zip.setProject(DEFAULT_PROJECT); zip.setDestFile(dest); FileSet fs = new FileSet(); fs.setProject(DEFAULT_PROJECT); fs.setDir(orgin); if(orgin.isDirectory()) fs.setDir(orgin);//设置压缩对象为文件夹 if(orgin.isFile()) fs.setFile(orgin);//设置压缩对象为文件 // fs.setIncludes("**/*.java"); // fs.setExcludes("**/*.xml"); zip.addFileset(fs); zip.execute(); } catch (Exception e) { log.error("压缩文件时,出现异常 :", e); } } /** * @param args */ public static void main(String[] args) { ZipUtil zipUtil=new ZipUtil();
//压缩 String orginPath2="d:\\\\sqlback\\d.sql" ; String destPath2 ="d:\\\\sqlback\\d.zip"; System.out.println("----------zip starting-----------"); zipUtil.zip(orginPath2, destPath2); System.out.println("----------zip success-----------"); //解压 String orginPath="d:\\\\sqlback\\d.zip"; String destPath="d:\\\\sqlback"; zipUtil.unZip(orginPath, destPath); System.out.println("----------un zip -----------");
}