SoFunction
Updated on 2025-03-08

The most practical and simple way to compress folders in Java

Java has a good class library for handling zip files. These classes are available in the package. The following Java sample program shows how to use the class to create a zip for an entire folder. We use recursively browsing the directory tree and then adding each file to the newly created zip file. Note that this example is only available for Java 1.7 and later.

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ; 
// Source code to create a zip file from a given folder
// This example program recursively adds all files in the folder
// Works only with Java 7 and above
public class ZipFolder {
    public static void main(String[] args) throws Exception {
        ZipFolder zf = new ZipFolder();         
        // Use the following paths for windows
        //String folderToZip = "c:\\demo\\test";
        //String zipName = "c:\\demo\\";         
        // Linux/mac paths
        String folderToZip = "/Users/jj/test";
        String zipName = "/Users/jj/";
        ((folderToZip), (zipName));
    } 
    // Uses  to create zip file
    private void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(()));
        (sourceFolderPath, new SimpleFileVisitor() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                (new ZipEntry((file).toString()));
                (file, zos);
                ();
                return ;
            }
        });
        ();
    }
}

In linux/mac, you can test newly created zip files with the following command

Decompression-t 

Instance extension

//Method 1:public void unZip(String zipfile) throws IOException {
  //Check whether it is a zip file and determine whether the file exists  checkFileName(zipfile);
  long startTime = ();
  File zfile=new File(zipfile);
  //Get the parent path of the file to be decompressed  String Parent=()+"/";
  FileInputStream fis=new FileInputStream(zfile);
  Charset charset = ("GBK");//Default UTF-8// CheckedInputStream cis = new CheckedInputStream(fis,new CRC32());
  ZipInputStream zis = new ZipInputStream(fis,charset);// Enter the source zip path  ZipEntry entry=null;
  BufferedOutputStream bos=null;
  while ((entry=())!=null) {
    if (()) {
    File filePath=new File(Parent+());
    //If the directory does not exist, create    if (!()) {
      ();
    }
    }else{
    FileOutputStream fos=new FileOutputStream(Parent+());
    bos=new BufferedOutputStream(fos);
    byte buf[] = new byte[1024];
    int len;
    while ((len = (buf)) != -1) {
      (buf, 0, len);
    }
    ();
    //It will refresh when closed    ();
    }
  }
  ();
  long endTime = ();
  ("The decompression is completed! The time required is:"+(endTime-startTime)+"ms");
// ("checksum:"+().getValue());  }

  private void checkFileName(String name) {
  //Does the file exist?  if (!new File(name).exists()) {
    ("The file to be unzipped does not exist!");
    (1);
  }
  // Determine whether it is a zip file  int index = (".");
  String str=(index+1);
  if (!"zip".equalsIgnoreCase(str)) {
    ("It's not a zip file, it can't be decompressed!");
    (1);
  } 
    }

This is the article about the most practical and simple method of Java compressing folders. For more information about Java compressing folders, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!