Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll learn how to zip a file into an archive and how to unzip the archive, all using core libraries provided by Java.

These core libraries are part of the java.util.zip package, where we can find all zipping- and unzipping-related utilities.

2. Zip a File

First, let’s look at a simple operation, zipping a single file.

For example, we’ll zip a file named test1.txt into an archive named compressed.zip.

Of course, we’ll first access the file from a disk:

public class ZipFile {

    public static void main(String[] args) throws IOException {
        String sourceFile = "test1.txt";
        FileOutputStream fos = new FileOutputStream("compressed.zip");
        ZipOutputStream zipOut = new ZipOutputStream(fos);

        File fileToZip = new File(sourceFile);
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
        zipOut.putNextEntry(zipEntry);

        byte[] bytes = new byte[1024];
        int length;
        while((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }

        zipOut.close();
        fis.close();
        fos.close();
    }
}

3. Zip Multiple Files

Next, let’s see how to zip multiple files into one zip file. We’ll compress test1.txt and test2.txt into multiCompressed.zip:

public class ZipMultipleFiles {

    public static void main(String[] args) throws IOException {
        String file1 = "src/main/resources/zipTest/test1.txt";
        String file2 = "src/main/resources/zipTest/test2.txt";
        final List<String> srcFiles = Arrays.asList(file1, file2);

        final FileOutputStream fos = new FileOutputStream(Paths.get(file1).getParent().toAbsolutePath() + "/compressed.zip");
        ZipOutputStream zipOut = new ZipOutputStream(fos);

        for (String srcFile : srcFiles) {
            File fileToZip = new File(srcFile);
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();
        }

        zipOut.close();
        fos.close();
    }
}

4. Zip a Directory

Now, let’s discuss how to zip an entire directory. Here, we’ll compress the zipTest folder into the dirCompressed.zip file:

public class ZipDirectory {
    public static void main(String[] args) throws IOException {
        String sourceFile = "zipTest";
        FileOutputStream fos = new FileOutputStream("dirCompressed.zip");
        ZipOutputStream zipOut = new ZipOutputStream(fos);

        File fileToZip = new File(sourceFile);
        zipFile(fileToZip, fileToZip.getName(), zipOut);
        zipOut.close();
        fos.close();
    }

    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zipOut.putNextEntry(new ZipEntry(fileName));
                zipOut.closeEntry();
            } else {
                zipOut.putNextEntry(new ZipEntry(fileName + "/"));
                zipOut.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
        fis.close();
    }
}

Note that:

  • To zip sub-directories, we iterate through them recursively.
  • Every time we find a directory, we append its name to the descendant’s ZipEntry name to save the hierarchy.
  • We also create a directory entry for every empty directory.

5. Append New Files to Zip File

Next, we’ll add a single file to an existing zip file. For example, let’s add file3.txt into compressed.zip:

String file3 = "src/main/resources/zipTest/file3.txt";
Map<String, String> env = new HashMap<>();
env.put("create", "true");

Path path = Paths.get(Paths.get(file3).getParent() + "/compressed.zip");
URI uri = URI.create("jar:" + path.toUri());

try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
    Path nf = fs.getPath("newFile3.txt");
    Files.write(nf, Files.readAllBytes(Paths.get(file3)), StandardOpenOption.CREATE);
}

In short, we mounted the zip file using .newFileSystem() provided by the FileSystems class, which has been available since JDK 1.7. Then, we created a newFile3.txt inside the compressed folder and added all the contents from file3.txt.

6. Unzip an Archive

Now, let’s unzip an archive and extract its contents.

For this example, we’ll unzip compressed.zip into a new folder named unzipTest:

public class UnzipFile {

    public static void main(String[] args) throws IOException {
        String fileZip = "src/main/resources/unzipTest/compressed.zip";
        File destDir = new File("src/main/resources/unzipTest");

        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
           // ...
        }

        zis.closeEntry();
        zis.close();
    }
}

Inside the while loop, we’ll iterate through each ZipEntry and first check if it’s a directory. If it is, then we’ll create the directory using the mkdirs() method; otherwise, we’ll continue with creating the file:

while (zipEntry != null) {
    File newFile = newFile(destDir, zipEntry);
    if (zipEntry.isDirectory()) {
        if (!newFile.isDirectory() && !newFile.mkdirs()) {
            throw new IOException("Failed to create directory " + newFile);
        }
    } else {
        // fix for Windows-created archives
        File parent = newFile.getParentFile();
        if (!parent.isDirectory() && !parent.mkdirs()) {
            throw new IOException("Failed to create directory " + parent);
        }

        // write file content
        FileOutputStream fos = new FileOutputStream(newFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
    }
    zipEntry = zis.getNextEntry();
}

One note here is that on the else branch, we’re also checking if the file’s parent directory exists. This is necessary for archives created on Windows, where the root directories don’t have a corresponding entry in the zip file.

Another critical point is in the newFile() method:

public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
    File destFile = new File(destinationDir, zipEntry.getName());

    String destDirPath = destinationDir.getCanonicalPath();
    String destFilePath = destFile.getCanonicalPath();

    if (!destFilePath.startsWith(destDirPath + File.separator)) {
        throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
    }

    return destFile;
}

The newFile() method guards against writing files to the file system outside the target folder. This vulnerability is called Zip Slip.

7. Conclusion

In this article, we illustrated how to use Java libraries for zipping and unzipping files.

The implementation of these examples can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.