Overview
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");
}
Other Supported Java Compression API
Use the Aspose.ZIP Java library to convert, merge, edit zip-file documents, extract data from the arhives, and more!
Support and Learning Resources
- Learning Resources
- Documentation
- Source Code
- API References
- Tutorial Videos
- Product Support
- Free Support
- Paid Support
- Blog
- Release Notes
- Why Aspose.ZIP for Java?
- Customers List
- Success Stories