Cancel ZIP archive creation

It may happen you want to cancel zip archive creation for various reasons. It just can take too long or you do not actually need some entries there.

Overview

There is an EventsBag class which are container for archive-related events. Now it supports one event - EntryCompressed ( getEntryCompressed/ setEntryCompressed). It raises after an archive entry has been compressed, and it cancelable.

Canceling long archive creation

Lets say you want your ZIP archive to be composed in about a minute. After some entry has been compressed check the time taken from the beginning of compression, and if it took more than a minute, cancel the process. The result archive would have already compressed entries including the one triggred the event.

 1try (Archive archive = new Archive()) {
 2    archive.createEntries("D:\\BigFolder");
 3    EventsBag eb = new EventsBag();
 4
 5    Instant starts = Instant.now();
 6
 7    eb.setEntryCompressed((sender, args) -> {
 8        if (starts.plusSeconds(60).isBefore(Instant.now()))
 9            args.setCancel(true);
10    });
11    ArchiveSaveOptions options = new ArchiveSaveOptions();
12    options.setEventsBag(eb);
13    archive.save("output.zip", options);
14}

Canceling after certain entry

If you want to cancel after particular entry has been compressed use following snippet:

 1try (Archive archive = new Archive()) {
 2    archive.createEntries("D:\\BigFolder");
 3    EventsBag eb = new EventsBag();
 4    eb.setEntryCompressed((sender, args) -> {
 5        System.out.println(args.getEntry().getName());
 6        if (args.getEntry().getName().equals("BigFolder\\last.bin"))
 7            args.setCancel(true);
 8    });
 9    ArchiveSaveOptions options = new ArchiveSaveOptions();
10    options.setEventsBag(eb);
11    archive.save("output.zip", options);
12}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.