`
linsl
  • 浏览: 70688 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

java压缩文件夹下的所有文件和选定文件

    博客分类:
  • java
阅读更多

 

  1. package zip;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5.   
  6. import org.apache.tools.zip.ZipEntry;  
  7. import org.apache.tools.zip.ZipOutputStream;  
  8.     
  9. public class test {     
  10.          
  11.     /**   
  12.      *    
  13.      * @param inputFileName 输入一个文件夹   
  14.      * @param zipFileName   输出一个压缩文件夹,打包后文件名字   
  15.      * @throws Exception   
  16.      */    
  17.     public void zip(String inputFileName, String zipFileName) throws Exception {     
  18.         System.out.println(zipFileName);     
  19.         zip(zipFileName, new File(inputFileName));     
  20.     }     
  21.     
  22.     private void zip(String zipFileName, File inputFile) throws Exception {     
  23.         ZipOutputStream out = new ZipOutputStream(new FileOutputStream(     
  24.                 zipFileName));     
  25.         zip(out, inputFile, "");     
  26.         System.out.println("zip done");     
  27.         out.close();     
  28.     }     
  29.     
  30.     private void zip(ZipOutputStream out, File f, String base) throws Exception {     
  31.         if (f.isDirectory()) {  //判断是否为目录     
  32.             File[] fl = f.listFiles();     
  33. //            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));     
  34.             out.putNextEntry(new ZipEntry(base + "/"));     
  35.             base = base.length() == 0 ? "" : base + "/";     
  36.             for (int i = 0; i < fl.length; i++) {     
  37.                 zip(out, fl[i], base + fl[i].getName());     
  38.             }     
  39.         } else {                //压缩目录中的所有文件     
  40. //            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));     
  41.             out.putNextEntry(new ZipEntry(base));     
  42.             FileInputStream in = new FileInputStream(f);     
  43.             int b;     
  44.             System.out.println(base);     
  45.             while ((b = in.read()) != -1) {     
  46.                 out.write(b);     
  47.             }     
  48.             in.close();     
  49.         }     
  50.     }     
  51.     
  52.     public static void main(String[] temp) {     
  53.         String inputFileName = "F:\\xxx\\excel\\多文件合并测试";    //你要压缩的文件夹     
  54.         String zipFileName = "D:\\test.zip";  //压缩后的zip文件     
  55.     
  56.         test book = new test();     
  57.         try {     
  58.             book.zip(inputFileName, zipFileName);     
  59.         } catch (Exception ex) {     
  60.             ex.printStackTrace();     
  61.         }     
  62.     }     
  63.     
  64. }    

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics