Reporting progress of compression

Progress Event Handler

The compression process may take a long time especially if the data size is huge. For zip archive, there is a CompressionProgressed event ( getCompressionProgressed/ setCompressionProgressed) to stay posted. This event relies on ProgressEventArgs which contains the number of proceeded bytes so far. This is how we can subscribe to this event using lambda expression:

1entry.setCompressionProgressed((sender, args) -> {
2    System.out.println(args.getProceededBytes() + " bytes compressed");
3});

Reporting Zip Progress Percentage

Each time the CompressionProgressed event raises we divide the ProceededBytes number by the length of the original file. Such we find the ratio of compressed bytes at the moment. Here is the full sample.

 1File source = new File("huge.bin");
 2try (Archive archive = new Archive()) {
 3    ArchiveEntry entry = archive.createEntry("huge.bin", source);
 4    final int[] percentReady = new int[1];
 5    entry.setCompressionProgressed((sender, args) -> {
 6        int percent = (int)((100 * (long)args.getProceededBytes()) / source.length());
 7        if (percent > percentReady[0])
 8        {
 9            System.out.println(percent + "% compressed");
10            percentReady[0] = percent;
11        }
12    });
13    archive.save("output.zip");
14}

Reporting 7z Progress Percentage

Similar approach is for 7z archive. Its entry has own methods for getting and setting the event ( getCompressionProgressed/ setCompressionProgressed)

 1File source = new File("huge.bin");
 2try (SevenZipArchive archive = new SevenZipArchive(new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings()))) {
 3    SevenZipArchiveEntry entry = archive.createEntry("huge.bin", source);
 4    final int[] percentReady = new int[1];
 5    entry.setCompressionProgressed((sender, args) -> {
 6        // sender is SevenZipArchiveEntry
 7        int percent = (int)((100 * (long)args.getProceededBytes()) / source.length());
 8        if (percent > percentReady[0])
 9        {
10            System.out.println(percent + "% compressed");
11            percentReady[0] = percent;
12        }
13    });
14    archive.save("output.zip");
15}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.