java中實現zip的壓縮與解壓縮。java自帶的 能實現的功能比較有限。java
本程序功能:實現簡單的壓縮和解壓縮,壓縮文件夾下的全部文件(文件過濾的話須要對File進一步細節處理)。正則表達式
對中文的支持須要使用java7或java8,能夠在ZipOutputStream和ZipInputStream中指定Charset參數,詳見API中的構造參數。ide
1.壓縮文件或文件夾spa
1 public void zip() throws IOException { 2 File fileSrc = new File("E:\\abc"); 3 File destFile = new File("E:\\abc.zip"); 4 zip(fileSrc,destFile); 5 }
1 public void zip(File fileSrc,File dectFile) throws IOException { 2 ZipOutputStream zipOutputStream = new ZipOutputStream(new CheckedOutputStream(new FileOutputStream(dectFile),new CRC32())); 3 String name = fileSrc.getName(); 4 zip(zipOutputStream, name,fileSrc); 5 zipOutputStream.flush(); 6 zipOutputStream.close(); 7 }
1 private void zip(ZipOutputStream zipOutputStream,String name, File fileSrc) throws IOException { 2 if (fileSrc.isDirectory()) { 3 File[] files = fileSrc.listFiles(new FilenameFilter() { //過濾文件 4 Pattern pattern = Pattern.compile(".+");//全部文件,正則表達式 5 @Override 6 public boolean accept(File dir, String name) { 7 return pattern.matcher(name).matches(); 8 } 9 }); 10 zipOutputStream.putNextEntry(new ZipEntry(name+"/")); // 建一個文件夾 11 name = name+"/"; 12 for (File f : files) { 13 zip(zipOutputStream,name+f.getName(),f); 14 } 15 }else { 16 17 zipOutputStream.putNextEntry(new ZipEntry(name)); 18 FileInputStream input = new FileInputStream(fileSrc); 19 byte[] buf = new byte[1024]; 20 int len = -1; 21 while ((len = input.read(buf)) != -1) { 22 zipOutputStream.write(buf, 0, len); 23 } 24 zipOutputStream.flush(); 25 input.close(); 26 } 27 }
2.解壓縮zip文件code
1 public void unzip() throws IOException { 2 File zipFile = new File("E:\\java.zip"); 3 String destDir = "E:\\java\\"; 4 unzip(zipFile,destDir); 5 }
1 private void unzip(File zipFile, String destDir) throws IOException { 2 ZipInputStream zipInputStream = new ZipInputStream(new CheckedInputStream(new FileInputStream(zipFile),new CRC32())); 3 ZipEntry zipEntry; 4 while ((zipEntry = zipInputStream.getNextEntry()) != null) { 5 System.out.println(zipEntry.getName()); 6 File f = new File(destDir + zipEntry.getName()); 7 if(zipEntry.getName().endsWith("/")){ 8 f.mkdirs(); 9 }else { 10 // f.createNewFile(); 11 FileOutputStream fileOutputStream = new FileOutputStream(f); 12 byte[] buf = new byte[1024]; 13 int len = -1; 14 while ((len = zipInputStream.read(buf)) != -1) { // 直到讀到該條目的結尾 15 fileOutputStream.write(buf, 0, len); 16 } 17 fileOutputStream.flush(); 18 fileOutputStream.close(); 19 } 20 zipInputStream.closeEntry(); //關閉該條目 21 } 22 zipInputStream.close(); 23 }