java中实现zip的压缩与解压缩。java自带的 能实现的功能比较有限。
本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理)。
对中文的支持需要使用java7或java8,可以在ZipOutputStream和ZipInputStream中指定Charset参数,详见API中的构造参数。
1.压缩文件或文件夹
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文件
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 }