Overwiew

To keep your archives up-to-date and relevant, consider deleting entries when necessary. Aspose.Zip via Java allows you to selectively remove or update specific files within the archive.

How to Remove File From Zip

Entries of ZIP archive can be deleted using deleteEntry pair of methods. Deleting an entry occurs without repacking, so other entries are not decompressed and compressed.
If you need to delete a single file from "archive.zip" using Java, the following code demonstrates how to achieve this. It performs the following actions
1. Opens the archive for editing: The code utilizes a try construct to automatically close the archive after the block of code is executed.
2. Iterates through entries: The subsequent lines implement a loop that iterates through the archive entries, deleting all but the last one.
3. Saves the modified archive: After the loop completes, the modified archive is saved to a new file named "last_entry.zip"
It is possible to save modified archive by the same path but this involves copying to temporary file. Entry deletion from multi-volume ZIP archives is not possible.

    try (Archive archive = new Archive("archive.zip")) {
        while (archive.getEntries().size() > 1)
            archive.deleteEntry(archive.getEntries().get(0));
        archive.save("last_entry.zip");
    }

Remove Files From a TAR Archive

Entries of tar archive can be deleted with similar deleteEntry methods.
This is the code for working with the TAR archive named "two_files.tar". It opens the archive for editing using the try-with-resources construct, which automatically closes the archive after the code block finishes execution. Next, the code deletes the record with index 0 from the archive, that is, the first file in the list of files or folders. The code then saves the modified archive as "single_file.tar". So this code creates a new TAR archive that contains only one of the files that were in the original "two_files.tar" archive.
Deleting entries from compressed tar archives, e.g. *.tar.gz requires decompression to plain *.tar archive first.

    try (TarArchive archive = new TarArchive("two_files.tar")) {
        archive.deleteEntry(0);
        archive.save("single_file.tar");
    }
  

Support and Learning Resources

  
  

Aspose.Zip offers individual archive processing APIs for other popular development environments, listed below: