Date:

Share:

Zip and Unzip Files in Java

Related Articles

In this tutorial, we will learn how to compress a file or directory into an archive and how to open the archive into a library using Java core libraries.

File zip

Let’s look at the example where we want to compress a single file into an archive:

public static void zipFile(Path fileToZip, Path zipFile) throws IOException 
    Files.createDirectories(zipFile.getParent());
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) 
        ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
        zipOutputStream.putNextEntry(zipEntry);
        if (Files.isRegularFile(fileToZip)) 
            Files.copy(fileToZip, zipOutputStream);
        
    

Reading the method below will cause a file to be compressed /cnc/toZip/picture1.png Into an archive /cnc/zip/singleFileArchive.zip: –

zipFile(Path.of("/cnc/toZip/picture1.png"), Path.of("/cnc/zip/singleFileArchive.zip"));

Note the following in this method: –

  1. Using the Java nio method Files.createDirectories() To create all the directories of the zip file if it does not exist. Not like the Files.createDirectory() Method, an exception is not discarded if it already exists.
  2. you’re sick ZipOutputStream In the try Block so that the closure of the streams will be handled by JVM.
  3. Using the Java nio method Files.copy() Copy the file to it ZipOutputStream, Makes your code concise.

Zip multiple files

Let’s look at the example where we want to compress multiple files into an archive:

public static void zipMultipleFiles(List<Path> filesToZip, Path zipFile) throws IOException 
    Files.createDirectories(zipFile.getParent());
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) 
        for(Path fileToZip: filesToZip)
            ZipEntry zipEntry = new ZipEntry(fileToZip.toFile().getName());
            zipOutputStream.putNextEntry(zipEntry);
            if (Files.isRegularFile(fileToZip)) 
                Files.copy(fileToZip, zipOutputStream);
            
        
    

Reading the method below will compress these two files picture1.png & picture2.png Into an archive /cnc/zip/multiFileArchive.zip: –

List<Path> filesToZip = Arrays.asList(Path.of("/cnc/toZip/picture1.png"), Path.of("/cnc/toZip/picture2.png"));

zipMultipleFiles(filesToZip, Path.of("/cnc/zip/multiFileArchive.zip"));

Note that we enter each file value ZipEntry Representing the archive file.

Compress all files and folders in the directory

Let’s look at the example where we want to compress all the files and folders within an archive directory:

public static void zipDirectory(Path directoryToZip, Path zipFile) throws IOException {
  Files.deleteIfExists(zipFile);
  Files.createDirectories(zipFile.getParent());
  try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) {
      if (Files.isDirectory(directoryToZip)) 
          Files.walk(directoryToZip).filter(path -> !Files.isDirectory(path)).forEach(path -> 
              ZipEntry zipEntry = new ZipEntry(directoryToZip.relativize(path).toString());
              try 
                  zipOutputStream.putNextEntry(zipEntry);
                  if (Files.isRegularFile(path)) 
                      Files.copy(path, zipOutputStream);
                  
                  zipOutputStream.closeEntry();
               catch (IOException e) 
                  System.err.println(e);
              
          );
      
  }
}

Reading the method below will compress all the files and folders inside /cnc/toZip Recursively into an archive /cnc/zip/fullDirectoryArchive.zip: –

zipDirectory(Path.of("/cnc/toZip"), Path.of("/cnc/zip/fullDirectoryArchive.zip"));

Note the following in this method: –

  1. Using Java NIO File Service Methods Files.deleteIfExists() and Files.createDirectories(), Which are safe to use and do not throw an exception if a file or directory does not exist.
  2. you’re sick ZipOutputStream In the try Block so that the closure of the streams will be handled by JVM.
  3. Using Java NIO Files.walk() Go through all the files and folders recursively in the directory using Java Streams.
  4. Put any file or directory entry in ZipEntry, Which represents the archive file.

Open an archive file

Let’s look at the example where we want to open an archive file into the destination directory:

public static void unzipDirectory(Path zipFile, Path targetDirectory) throws IOException {
    if (!Files.exists(zipFile)) 
        return;
    
    deleteDirectoryRecursively(targetDirectory);
    Files.createDirectory(targetDirectory);
    try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile))) 
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) 
            final Path toPath = targetDirectory.resolve(entry.getName());
            if (entry.isDirectory()) 
                Files.createDirectory(toPath);
             else 
                if (!Files.exists(toPath.getParent())) 
                    Files.createDirectories(toPath.getParent());
                
                Files.copy(zipInputStream, toPath);
            
        
    
}

private static void deleteDirectoryRecursively(Path dir) throws IOException 
    if (Files.exists(dir)) 
        Files.walk(dir).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
    

Reading the method below will hack all the files and folders inside fullDirectoryArchive.zip Recursively into the library /cnc/toUnzip: –

unzipDirectory(Path.of("/cnc/zip/fullDirectoryArchive.zip"), Path.of("/cnc/toUnzip"));

Note the following in this method: –

  1. Perform initial verifications for example return and do nothing if zip file does not exist, delete the target directory recursively if it already exists.
  2. you’re sick ZipInputStream In the try Block so that the closure of the streams will be handled by JVM.
  3. Come back through ZipEntry, Which is an archive file representation and has all the archive information: –
    – If it’s a directory then create this directory
    – If it’s a file then create all its parent directories and then copy this file

This is this guide. Thanks for reading and enjoyable learning!

Download the ZipFileUtil.java Having all these methods and start using your code.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles