Java使用Zip包压缩文件示例

来源:互联网 发布:图片横向滚动js代码 编辑:程序博客网 时间:2024/06/05 05:40

Java使用Zip包压缩文件示例

  1. public static void zip() throws FileNotFoundException, IOException {   
  2.     File root = new File("svn-1.6");   
  3.     ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(root.getPath()+".zip"));   
  4.        
  5.     zipDirectory(root,zipOutputStream);   
  6.        
  7.     zipOutputStream.close();   
  8. }   
  9.   
  10. private static void zipDirectory(File root,ZipOutputStream zipOutputStream) throws IOException{   
  11.     String zipPath = "";   
  12.     zipDirectory(zipPath,root,zipOutputStream);   
  13. }   
  14.   
  15. private static void zipDirectory(String basePath,File root,ZipOutputStream zipOutputStream) throws IOException{   
  16.     if(basePath.length()>0){   
  17.         basePath += "/";   
  18.     }   
  19.     File[] files = root.listFiles();   
  20.     for (int i = 0; i < files.length; i++) {   
  21.         File file = files[i];   
  22.         if(file.isFile()){   
  23.             System.out.println(file.getPath());   
  24.             ZipEntry zipEntry = new ZipEntry(basePath + file.getName());   
  25.             zipOutputStream.putNextEntry(zipEntry);   
  26.                
  27.             FileInputStream inputStream = new FileInputStream(file);   
  28.             int count;byte[] buffer = new byte[1024];   
  29.             while((count = inputStream.read(buffer, 0, buffer.length))>0){   
  30.                 zipOutputStream.write(buffer, 0, count);   
  31.             }   
  32.             inputStream.close();   
  33.         }else if(file.isDirectory()){   
  34.             ZipEntry zipEntry = new ZipEntry(basePath + file.getName()+"/");   
  35.             zipOutputStream.putNextEntry(zipEntry);   
  36.             zipDirectory(basePath + file.getName(),file,zipOutputStream);   
  37.         }   
  38.     }   
  39. }  
原创粉丝点击