• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | zip: Extract a Zip file
  1. Maven - POM Configuration
  2. Notes
  3. Extract a Zip file

  1. Maven - POM Configuration
    Before you can use the java zip API, you need to add some dependencies to your "pom.xml" file.

    Here's the minimal dependencies needed in order for the following examples to work:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.18.0</version>
    </dependency>
  2. Notes
    Here's the structure of the Zip file "abc.zip" used in the example below:
    #|+ abc
    #   |+ abc1
    #      |+ abc1_1.txt
    #   |+ abc2
    #      |+ abc2_1.txt
  3. Extract a Zip file
    // this code will read the zip file "abc.zip" and extract it in the temp folder.
    final String zipPath = "/apps/abc.zip";
    
    final Path tempDirectoryPath = Files.createTempDirectory("temp_");
    
    try (final InputStream inputStream = new FileInputStream(zipPath);
            final ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
        ZipEntry zipEntry = zipInputStream.getNextEntry();
    
        while (zipEntry != null) {
            final String zipEntryName = zipEntry.getName();
    
            final File file = new File(tempDirectoryPath.toFile(), zipEntryName);
    
            if (zipEntry.isDirectory()) {
                System.out.println("Creating the directory \"" + file.getPath());
    
                file.mkdir();
            } else {
                System.out.println("Creating the file \"" + file.getPath());
    
                try (final FileOutputStream fileOutputStream = new FileOutputStream(file)) {
                    IOUtils.copy(zipInputStream, fileOutputStream);
                }
            }
    
            zipEntry = zipInputStream.getNextEntry();
        }
    }
    Output:
    Creating the directory "/temp/temp_8417875863245211368/abc
    Creating the directory "/temp/temp_8417875863245211368/abc/abc1
    Creating the file "/temp/temp_8417875863245211368/abc/abc1/abc1_1.txt
    Creating the directory "/temp/temp_8417875863245211368/abc/abc2
    Creating the file "/temp/temp_8417875863245211368/abc/abc2/abc2_1.txt
© 2025  mtitek