java 生成 zip格式 压缩文件

560阅读 0评论2022-05-25 fhadmin
分类:Java


点击(此处)折叠或打开


  1. ackage org.fh.util;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.util.zip.ZipEntry;
  7. import java.util.zip.ZipOutputStream;
  8.  
  9. /**
  10.  * 说明:java压缩成zip
  11.  * 作者:FH Admin
  12.  * from:fhadmin.cn
  13.  */
  14. public class FileZip {
  15.  
  16.     /**
  17.      * @param inputFileName 你要压缩的文件夹(整个完整路径)
  18.      * @param zipFileName 压缩后的文件(整个完整路径)
  19.      * @throws Exception
  20.      */
  21.     public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
  22.         zip(zipFileName, new File(inputFileName));
  23.         return true;
  24.     }
  25.  
  26.     private static void zip(String zipFileName, File inputFile) throws Exception {
  27.         ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
  28.         zip(out, inputFile, "");
  29.         out.flush();
  30.         out.close();
  31.     }
  32.  
  33.     private static void zip(ZipOutputStream out, File f, String base) throws Exception {
  34.         if (f.isDirectory()) {
  35.             File[] fl = f.listFiles();
  36.             out.putNextEntry(new ZipEntry(base + "/"));
  37.             base = base.length() == 0 ? "" : base + "/";
  38.             for (int i = 0; i < fl.length; i++) {
  39.                 zip(out, fl[i], base + fl[i].getName());
  40.             }
  41.         } else {
  42.             out.putNextEntry(new ZipEntry(base));
  43.             FileInputStream in = new FileInputStream(f);
  44.             int b;
  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.          try {
  54.              zip("E:\\ftl","E:\\test.zip");//你要压缩的文件夹 和 压缩后的文件
  55.              }catch (Exception ex) {
  56.                  ex.printStackTrace();
  57.              }
  58.         }
  59. }


上一篇:SpringBoot 前后端分离 实现验证码操作
下一篇:springboot 整合国产达梦数据库配置代码