Java单文件下支持多目录压缩类

时间:2021-04-23 12:50:06
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 多层级目录压缩至ZIP文件中
 * @since
 * @author Gloomy.H
 */

public class FileIntoZipUtil {
  //输出文件绝对路径tmp.zip
  private final static File outFile = new File("C:/tmp/tmp.zip");


  private static File inFile = null;
   
  /**
   * 初始化,构建相应目录和文件
   */

  public static  void init(){
    if(!outFile.exists()){
      try {
        if(!outFile.getParentFile().exists()){
          outFile.getParentFile().mkdirs();
        }
        outFile.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
        return;
      }
    }
  }
  
  public static void createZip() {
    init();
    //输入文件
    inFile= new File("H:/test");
    ZipOutputStream zipOut = null;
    try {
      zipOut = new ZipOutputStream(new FileOutputStream(outFile));
      //递归压缩文件
      convertZip(inFile, zipOut, null);
      zipOut.close();
    } catch (FileNotFoundException e) {
      System.out.println("Not find the File");
    } catch (IOException e) {
      System.out.println("There is a Exception in IO");
    }
  }


  public static void convertZip(File file,
                                ZipOutputStream zipOut,
                                String path) {
    FileInputStream fin = null;
    if (file.isDirectory()) {
      File[] fileList = file.listFiles();
      for (File f : fileList) {
        if (null != path) {
          convertZip(f, zipOut, path + "/" + file.getName());
        } else {
          convertZip(f, zipOut, file.getName());
        }
      }
    } else {
      try {
        zipOut.putNextEntry(new ZipEntry(path + "/" + file.getName()));
        fin = new FileInputStream(file);
        int n = -1;
        while ((n = fin.read()) != -1) {
          zipOut.write(n);
        }
        zipOut.closeEntry();
        fin.close();
      } catch (IOException e) {
        System.out.println("There is a Exception in IO");
        e.printStackTrace();
        return;
      }
    }
  }
}