正确的 zip 压缩与解压代码
生活随笔
收集整理的這篇文章主要介紹了
正确的 zip 压缩与解压代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
網上流傳的zip壓縮與解壓 的代碼有非常大的問題 盡管使用了ant進行壓縮與解壓,可是任務的流程還是用的java.util.zip 的方式寫的,我在使用的過程中遇到了壓縮的文件夾結構有誤,甚至出現不同解壓軟件顯示的文件夾結構不同的窘境。
以下給出使用org.apache.tools.ant.taskdefs.Zip;和org.apache.tools.ant.taskdefs.Expand 的壓縮和解壓過程。
import java.io.File;import org.apache.tools.ant.BuildException; 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;public class Zipper {public final static String encoding = "GBK";// 壓縮public static void zip(String srcPathname, String zipFilepath)throws BuildException, RuntimeException {File file = new File(srcPathname);if (!file.exists())throw new RuntimeException("source file or directory "+ srcPathname + " does not exist.");Project proj = new Project();FileSet fileSet = new FileSet();fileSet.setProject(proj);// 推斷是文件夾還是文件if (file.isDirectory()) {fileSet.setDir(file);// ant中include/exclude規則在此都能夠使用// 比方:// fileSet.setExcludes("**/*.txt");// fileSet.setIncludes("**/*.xls");} else {fileSet.setFile(file);}Zip zip = new Zip();zip.setProject(proj);zip.setDestFile(new File(zipFilepath));zip.addFileset(fileSet);zip.setEncoding(encoding);zip.execute();}// 解壓縮public static void unzip(String zipFilepath, String destDir)throws BuildException, RuntimeException {if (!new File(zipFilepath).exists())throw new RuntimeException("zip file " + zipFilepath+ " does not exist.");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();}public static void main(String []args){unzip("D:\\123.zip","D:\\123");zip("D:\\upload","D:\\upload.zip");} }
?
轉載于:https://www.cnblogs.com/mfrbuaa/p/3864774.html
總結
以上是生活随笔為你收集整理的正确的 zip 压缩与解压代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抽象线程之Parallel类
- 下一篇: 用js使得输入框input只能输入数字