Remove File from ZIP in Java

This brief topic explains how to remove file from ZIP in Java. It includes all the information like preparing the environment and a code snippet to delete ZIP file in Java. Besides, this workflow can be followed in any operating system like macOS, Windows, or Linux, where JDK is configured.

Steps to Delete File From ZIP in Java

  1. Set up the system by configuring Aspose.ZIP in your environment
  2. Declare an object of the Archive class to load the input archive
  3. Loop through all the contents in the archive and filter the files with matching string
  4. Delete all the entries in the list with the deleteEntry method
  5. Write the updated ZIP file

These steps showcase how easily you can delete file from ZIP in Java. It initiates the process by creating a list of all the entries that match the criteria specified by the user. Then, all such files in that list are deleted from the list before saving the output ZIP archive.

Code to Delete ZIP File in Java

// Load the ZIP archive
var archive = new com.aspose.zip.Archive("archive.zip");
// List to keep files to be deleted
List<com.aspose.zip.ArchiveEntry> entriesToDelete = new ArrayList<>();
// Loop through ZIP entries
for(com.aspose.zip.ArchiveEntry entry : archive.getEntries())
{
// Add file/folder into list
if(entry.getName().toLowerCase().contains(“source”))
{
entriesToDelete.add(entry);
}
}
// Delete all listed entries
for(var entry : entriesToDelete)
{
archive.deleteEntry(entry);
}
// Save updated archive
archive.save("updated-archive.zip");

This sample code elaborates on how to remove a ZIP file in Java. Whereas you can customize it further to delete a particular file by using its index number. For example, it can help you delete any file in the archive when there are different ZIP directories with different file names.

This article has explained how to delete zipped files in Java. However, if you want to create a ZIP file, then visit the article on Create ZIP in Java.