Zip or UnZip Folders in Java - Compress and Decompress Directory

Aspose.ZIP API lets you compress and decompress files without worrying about the underlying file structure. This article shows working with single as well as multiple file compression.

Compressing Directory

Compressing Directory Contents

1try (FileOutputStream zipFile  = new FileOutputStream(dataDir + "CompressDirectory_out.zip")) {
2    try (Archive archive = new Archive()) {
3        File corpus = new File(dataDir + "CanterburyCorpus");
4        archive.createEntries(corpus);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Extracting Compressed Directory Archive

1try (FileInputStream zipFile = new FileInputStream(dataDir + "CompressDirectory_out.zip")) {
2    try (Archive archive = new Archive(zipFile)) {
3        archive.extractToDirectory(dataDir + "DecompressFolder_out");
4    }
5} catch (IOException ex) {
6    System.out.println(ex);
7}

Compress Files by File Info

 1try (FileOutputStream zipFile  = new FileOutputStream(dataDir + "CompressFilesByFileInfo_out.zip")) {
 2    File fi1 = new File(dataDir + "alice29.txt");
 3    File fi2 = new File(dataDir + "fields.c");
 4    try (Archive archive = new Archive()) {
 5        archive.createEntry("alice29.txt", fi1);
 6        archive.createEntry("fields.c", fi2);
 7        ArchiveSaveOptions options = new ArchiveSaveOptions();
 8        options.setEncoding(StandardCharsets.US_ASCII);
 9        archive.save(zipFile, options);
10    }
11} catch (IOException ex) {
12    System.out.println(ex);
13}

Extract Archives with Different Entry Archives

1try (FileInputStream zipFile = new FileInputStream(dataDir + "\\different_password.zip")) {
2    try (Archive archive = new Archive(zipFile)) {
3        archive.getEntries().get(0).extract(dataDir + "alice29_extracted_pass_out.txt", "first_pass");
4        archive.getEntries().get(1).extract(dataDir + "asyoulik_extracted_pass_out.txt", "second_pass");
5    }
6} catch (IOException ex) {
7    System.out.println(ex);
8}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.