Java implementation of zip compression and decompression tool class example

  • 2020-12-19 21:05:39
  • OfStack

The zip compression and decompression tool class implemented by Java is described. To share for your reference, the details are as follows:


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class ZipUtil {
  private static final int BUFFEREDSIZE = 1024;
  /**
   *  The compressed file 
   *
   * @param zipFileName
   *       Save the zip file path 
   * @param filePath
   *       The folder or file path that needs to be compressed 
   * @param isDelete
   *       Whether to delete the source file 
   * @throws Exception
   */
  public void zip(String zipFileName, String filePath, boolean isDelete) throws Exception {
    zip(zipFileName, new File(filePath), isDelete);
  }
  /**
   *  The compressed file 
   *
   * @param zipFileName
   *       Save the zip file path 
   * @param inputFile
   *       A folder or file that needs to be compressed 
   * @param isDelete
   *       Whether to delete the source file 
   * @throws Exception
   */
  public void zip(String zipFileName, File inputFile, boolean isDelete) throws Exception {
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
    if (!inputFile.exists()) {
      throw new FileNotFoundException(" No file to be compressed was found in the specified path! ");
    }
    zip(out, inputFile, "", isDelete);
    out.close();
  }
  /**
   *  Recursive compression method 
   *
   * @param out
   *       Compress packet output stream 
   * @param f
   *       Files that need to be compressed 
   * @param base
   *       Compressed path 
   * @param isDelete
   *       Whether to delete the source file 
   * @throws Exception
   */
  private void zip(ZipOutputStream out, File inputFile, String base, boolean isDelete) throws Exception {
    if (inputFile.isDirectory()) { //  If it's a directory 
      File[] inputFiles = inputFile.listFiles();
      out.putNextEntry(new ZipEntry(base + "/"));
      base = base.length() == 0 ? "" : base + "/";
      for (int i = 0; i < inputFiles.length; i++) {
        zip(out, inputFiles[i], base + inputFiles[i].getName(), isDelete);
      }
    } else { //  If it's a file 
      if (base.length() > 0) {
        out.putNextEntry(new ZipEntry(base));
      } else {
        out.putNextEntry(new ZipEntry(inputFile.getName()));
      }
      FileInputStream in = new FileInputStream(inputFile);
      try {
        int len;
        byte[] buff = new byte[BUFFEREDSIZE];
        while ((len = in.read(buff)) != -1) {
          out.write(buff, 0, len);
        }
      } catch (IOException e) {
        throw e;
      } finally {
        in.close();
      }
    }
    if (isDelete) {
      inputFile.delete();
    }
  }
  /**
   *  unzip 
   *
   * @param zipFilePath
   *       Packet path 
   * @param fileSavePath
   *       Unpack the path 
   * @param isDelete
   *       Whether to delete the source file 
   * @throws Exception
   */
  public void unZip(String zipFilePath, String fileSavePath, boolean isDelete) throws Exception {
    try {
      (new File(fileSavePath)).mkdirs();
      File f = new File(zipFilePath);
      if ((!f.exists()) && (f.length() <= 0)) {
        throw new Exception(" The file you want to unzip does not exist !");
      }
      ZipFile zipFile = new ZipFile(f);
      String strPath, gbkPath, strtemp;
      File tempFile = new File(fileSavePath);//  Start with the current directory 
      strPath = tempFile.getAbsolutePath();//  The absolute position of the output 
      Enumeration<ZipEntry> e = zipFile.getEntries();
      while (e.hasMoreElements()) {
        org.apache.tools.zip.ZipEntry zipEnt = e.nextElement();
        gbkPath = zipEnt.getName();
        if (zipEnt.isDirectory()) {
          strtemp = strPath + File.separator + gbkPath;
          File dir = new File(strtemp);
          dir.mkdirs();
          continue;
        } else {
          //  Read and write files 
          InputStream is = zipFile.getInputStream(zipEnt);
          BufferedInputStream bis = new BufferedInputStream(is);
          gbkPath = zipEnt.getName();
          strtemp = strPath + File.separator + gbkPath;
          //  Build directory 
          String strsubdir = gbkPath;
          for (int i = 0; i < strsubdir.length(); i++) {
            if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
              String temp = strPath + File.separator + strsubdir.substring(0, i);
              File subdir = new File(temp);
              if (!subdir.exists())
                subdir.mkdir();
            }
          }
          FileOutputStream fos = new FileOutputStream(strtemp);
          BufferedOutputStream bos = new BufferedOutputStream(fos);
          int len;
          byte[] buff = new byte[BUFFEREDSIZE];
          while ((len = bis.read(buff)) != -1) {
            bos.write(buff, 0, len);
          }
          bos.close();
          fos.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
    if (isDelete) {
      new File(zipFilePath).delete();
    }
  }
// public static void main(String[] args) {
//   ZipUtil cpr = new ZipUtil();
//   try {
//     cpr.zip("C:/Users/Lenovo User/Desktop/test Chinese .zip", "C:/Users/Lenovo User/Desktop/ New folder ", false);
//     cpr.unZip("C:/Users/Lenovo User/Desktop/test Chinese .zip", "C:/Users/Lenovo User/Desktop/ New folder 2", false);
//   } catch (Exception e) {
//     e.printStackTrace();
//   }
//
// }
}

For more information about java algorithm, please refer to Java File and directory Operation Skills Summary, Java Data Structure and Algorithm Tutorial, Java Operation Skills Summary of DOM Nodes and Java Cache Operation Skills Summary.

I hope this article has been helpful in java programming.


Related articles: