Delete Files from ZIP Archive – Java Example

In this tutorial, we will discuss how to delete files from a ZIP Archive using ZPFS (Zip File System Provider) and Java NIO, with a suitable example. We will provide a step by step guide for deleting entries in a ZIP file. These steps are captured below:


Steps to Delete ZIP File Entries through Java Program - ZPFS - NIO Example
Steps to Delete ZIP File Entries through Java Program - ZPFS - NIO Example

1.Define ZIP File System Properties


We have discussed this step in detail in our extract ZIP File using ZPFS tutorial. Since we are dealing with existing ZIP files, all we need to do here is to set the “create” property to false and define the encoding format. The Java code segment is shown below:

        /* Define ZIP File System Properies in HashMap */    
        Map<String, String> zip_properties = new HashMap<>(); 
        /* We want to read an existing ZIP File, so we set this to False */
        zip_properties.put("create", "false");
        /* Specify the encoding as UTF -8 */
        zip_properties.put("encoding", "UTF-8"); 


2.URI to ZIP File


In order to delete entries from a ZIP file, we need a pointer that tells us where the physical file is located. Using this pointer and the properties in step 1, we will be able to create a Zip File System in Java. So, we create a URI object and point to the file on disk. The Java code segment to do this is shown below:


        /* Specify the path to the ZIP File that you want to read as a File System */
        URI zip_disk = URI.create("jar:file:/my_zip_file.zip");        

A screenshot of the ZIP file from which we want to delete an entry is shown below:

Input ZIP File - Delete ZIP Entry - Example
Input ZIP File - Delete ZIP Entry - Example
We will write some code to delete “source.sql” file alone from this ZIP Archive.


3.Create ZIP File System


The next step is to create ZIP File system. We have done this many times in our earlier tutorials. Once the File System is created, deleting documents from ZIP file is as simple as deleting a file from a folder in Java. The Java code segment to create a ZIP file system is shown below:

        try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties)) {


4.Delete ZIP File Entry


In step 3, we created the ZIP File System in Java using NIO. Our aim is to delete “source.sql” file from the ZIP file. Every file inside a ZIP Archive is a ZIP entry. Manipulating ZIP entries is an easy task with the introduction of ZPFS. The code segment to delete a ZIP Entry in Java is shown below:


            /* Get the Path inside ZIP File to delete the ZIP Entry */
            Path pathInZipfile = zipfs.getPath("source.sql");
            System.out.println("About to delete an entry from ZIP File" + pathInZipfile.toUri() ); 
            /* Execute Delete */
            Files.delete(pathInZipfile);
            System.out.println("File successfully deleted");   


You retrieve the path to the ZIP entry using getPath method. Once this is done, you can use delete method in java.nio.file.Files class, to delete the ZIP Entry. Java automatically adjusts other entries in the ZIP file and you don’t need any further coding! Easy.



5.Delete ZIP Entry From ZIP Archive – Java NIO ZPFS – Complete Program


The complete Java program to delete an entry from a ZIP Archive is shown below

import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;
import java.nio.file.StandardCopyOption;
public class ZPFSDelete {
    public static void main(String [] args) throws Exception {
        
        /* Define ZIP File System Properies in HashMap */    
        Map<String, String> zip_properties = new HashMap<>(); 
        /* We want to read an existing ZIP File, so we set this to False */
        zip_properties.put("create", "false"); 
        
        /* Specify the path to the ZIP File that you want to read as a File System */
        URI zip_disk = URI.create("jar:file:/my_zip_file.zip");
        
        /* Create ZIP file System */
        try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties)) {
            /* Get the Path inside ZIP File to delete the ZIP Entry */
            Path pathInZipfile = zipfs.getPath("source.sql");
            System.out.println("About to delete an entry from ZIP File" + pathInZipfile.toUri() ); 
            /* Execute Delete */
            Files.delete(pathInZipfile);
            System.out.println("File successfully deleted");   
        } 
    }
}

The output of this program in terms of logs is show below:

About to delete an entry from ZIP File jar:file:///C:/my_zip_file.zip!/source.sql

File successfully deleted

A screenshot of the resulting ZIP file is shown below:

Output ZIP File with ZIP Entries Removed

That is it. Simple steps to code and you have successfully deleted an entry from ZIP file in Java now. In the next tutorial we will discuss how to rename ZIP Entries in Java with the same feature. If you have a question on this article meanwhile, you can post it in the comments section of this blog.

3 comments:

  1. This solution doesn't work if there is a space in the file name. The error that is thrown is on the following line:

    try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties)) {

    The exception that is thrown is

    Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in path at index 36: file:///Users/Will/Documents/Eclipse Workspace/Test.jar"

    Any way to get around this?

    ReplyDelete
  2. @Will,

    Do you have a space in the ZIP file or in the contents of the ZIP file?

    Can you post your full code?

    ReplyDelete
  3. Could you please suggest some solutions how to delete file inside a folder in the zip file?

    ReplyDelete