运用JDK中 ZipInputStream类实现压缩文件的解压缩功能

来源:互联网 发布:重庆时时彩平台源码 编辑:程序博客网 时间:2024/04/29 10:12
将压缩文件log.zip 解压到output文件夹: 
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.zip.ZipEntry;  
  6. import java.util.zip.ZipInputStream;  
  7.   
  8. public class UnZipExample {  
  9.   
  10.     public static void main(String[] args) {  
  11.         String zipFile = "log.zip";  
  12.         String outputFolder = "output";  
  13.         byte[] buffer = new byte[1024];  
  14.         try {  
  15.             File folder = new File(outputFolder);  
  16.             if (!folder.exists()) {  
  17.                 folder.mkdir();  
  18.             }  
  19.             //获取zip文件  
  20.             ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));  
  21.             //获取zip文件里面的文件列表  
  22.             ZipEntry ze = zis.getNextEntry();  
  23.             while (ze != null) {  
  24.                 String fileName = ze.getName();  
  25.                 File newFile = new File(outputFolder + File.separator + fileName);  
  26.                 System.out.println("文件解压 : " + newFile.getAbsoluteFile());  
  27.                 //获取文件名中的路径创建文件夹  
  28.                 new File(newFile.getParent()).mkdirs();  
  29.                 FileOutputStream fos = new FileOutputStream(newFile);  
  30.                 int len;  
  31.                 while ((len = zis.read(buffer)) > 0) {  
  32.                     fos.write(buffer, 0, len);  
  33.                 }  
  34.                 fos.close();  
  35.                 ze = zis.getNextEntry();  
  36.             }  
  37.             zis.closeEntry();  
  38.             zis.close();  
  39.             System.out.println("End");  
  40.         } catch (IOException ex) {  
  41.             ex.printStackTrace();  
  42.         }  
  43.     }  
  44. }