Zip or UnZip Files in Java

Overview

This article will teach you how to programmatically compress Zip files using a variety of methods utilising Java API and sample code. You will learn how to zip or compress one or more files, as well as how to zip files simultaneously. You will also learn how to decompress or unzip files as well.

Zip or Compress files in Java and Decompress or Unzip files in Java

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 Files

Compressing Single File

Steps: Compressing Single File in Java

  1. Create a file output stream with the desired name of your output zip file.
  2. Create file input stream of the data file to be compressed.
  3. Create an instance of Archive class and pass it instance of ArchiveEntrySettings class.
  4. Add data file created in step 2 using Archive.createEntry method.
  5. Zip the data file using Archive.save method and pass it the file stream created in step 1.
 1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "CompressSingleFile_out.zip")) {
 2    //File to be added to archive
 3    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
 4        try (Archive archive = new Archive(new ArchiveEntrySettings())) {
 5            archive.createEntry("alice29.txt", source1);
 6            archive.save(zipFile);
 7        }
 8    }
 9} catch (IOException ex) {
10    System.out.println(ex);
11}

Compressing Multiple Files

Steps: Compressing Multiple Files in Java

  1. Create a file stream with the desired name of your output zip file.
  2. Create file stream of the first data file to be compressed.
  3. Create file stream of the second data file to be compressed.
  4. Create an instance of Archive class.
  5. Add data files created in step 2 and step 3 using Archive.createEntry method.
  6. Create an instance of ArchiveSaveOptions class.
  7. Zip the data files using Archive.save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "CompressSingleFile_out.zip")) {
 2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
 3        try (FileInputStream source2 = new FileInputStream(dataDir + "asyoulik.txt")) {
 4            try (Archive archive = new Archive(new ArchiveEntrySettings())) {
 5                archive.createEntry("alice29.txt", source1);
 6                archive.createEntry("asyoulik.txt", source2);
 7                ArchiveSaveOptions options = new ArchiveSaveOptions();
 8                options.setEncoding(StandardCharsets.US_ASCII);
 9                options.setArchiveComment("There are two poems from Canterbury corpus");
10                archive.save(zipFile, options);
11            }
12        }
13    }
14} catch (IOException ex) {
15    System.out.println(ex);
16}

Compress Files by File Info

Steps: Compress Files by File Info in Java

  1. Open a file output stream with the desired name of your output zip file.
  2. Create File object of your first data file to be compressed.
  3. Create File object of your second data file to be compressed.
  4. Create an instance of Archive class.
  5. Add data files created in step 2 and step 3 using Archive.createEntry method.
  6. Create an instance of ArchiveSaveOptions class.
  7. Zip the data files using Archive.save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 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 ignored) {
12    System.out.println(ex);
13}

Storing Files to Archives without Compression

Steps: Storing Files to Archives without Compression using Java

  1. Open a file output stream with the desired name of your output zip file.
  2. Create File objects for your data files to be stored in archive.
  3. Create an instance of ArchiveEntrySettings class and pass it instance of StoreCompressionSettings class.
  4. Create an instance of Archive class and pass it instance of ArchiveEntrySettings class created in above step.
  5. Add File objects created in step 2 using Archive.createEntry method.
  6. Create instance of ArchiveSaveOptions and set encoding to StandardCharsets.US_ASCII using ArchiveSaveOptions.setEncoding method.
  7. Zip the data files using Archive.save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "StoreMultipleFilesWithoutCompression_out.zip")) {
 2    File fi1 = new File(dataDir + "alice29.txt");
 3    File fi2 = new File(dataDir + "fields.c");
 4    try (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings()))) {
 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 ignored) {
12    System.out.println(ex);
13}

Using Parallelism to Compress Files

Steps: Using Parallelism to Compress Files using Java

  1. Open a file output stream with the desired name of your output zip file.
  2. Open file input streams for your first and second data files to be compressed.
  3. Create an instance of Archive class.
  4. Add data files created in step 2 using Archive.createEntry method.
  5. Create an instance of ParallelOptions and set ParallelCompressionMode.Always using ParallelOptions.setParallelCompressInMemory method.
  6. Create instance of ArchiveSaveOptions and set parallel options with the above instance using ArchiveSaveOptions.setParallelOptions method.
  7. Zip the data files using Archive.save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "UsingParallelismToCompressFiles_out.zip")) {
 2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
 3        try (FileInputStream source2 = new FileInputStream(dataDir + "asyoulik.txt")) {
 4            try (Archive archive = new Archive(new ArchiveEntrySettings())) {
 5                archive.createEntry("alice29.txt", source1);
 6                archive.createEntry("asyoulik.txt", source2);
 7                ParallelOptions parallelOptions = new ParallelOptions();
 8                parallelOptions.setParallelCompressInMemory(ParallelCompressionMode.Always);
 9                ArchiveSaveOptions options = new ArchiveSaveOptions();
10                options.setParallelOptions(parallelOptions);
11                options.setEncoding(StandardCharsets.US_ASCII);
12                options.setArchiveComment("There are two poems from Canterbury corpus");
13                archive.save(zipFile, options);
14            }
15        }
16    }
17} catch (IOException ex) {
18    System.out.println(ex);
19}

LZMA Compression within ZIP Archive

The Lempel–Ziv–Markov chain algorithm (LZMA) is an algorithm used to perform lossless data compression. LZMA uses a dictionary compression algorithm, the compressed stream is a stream of bits. LZMA compression within the ZIP archive allows ZIP containers to contain LZMA compressed entries. The following code example shows the implementation of LZMA compression using Aspose.ZIP API.

Steps: LZMA Compression within ZIP Archive using Java

  1. Open a file output stream with the desired name of your output zip file.
  2. Create an instance of ArchiveEntrySettings class and pass it instance of LzmaCompressionSettings class.
  3. Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
  4. Add data files to be compressed via file paths using Archive.createEntry method.
  5. Zip the data files using Archive.save method.
1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "LZMACompression_out.zip")) {
2    try (Archive archive = new Archive(new ArchiveEntrySettings(new LzmaCompressionSettings()))) {
3        archive.createEntry("sample.txt", dataDir + "sample.txt");
4        archive.save(zipFile);
5    }
6} catch (IOException ignored) {
7    System.out.println(ex);
8}

BZip2 Compression within ZIP Archive

BZip2 compression settings allow ZIP container to contain BZip2 compressed entries. The following code example shows the implementation of BZip2 compression using Aspose.ZIP API.

Steps: BZip2 Compression within ZIP Archive using Java

  1. Open a file output stream with the desired name of your output zip file.
  2. Create an instance of ArchiveEntrySettings class and pass it instance of Bzip2CompressionSettings class.
  3. Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
  4. Add data files to be compressed via file paths using Archive.createEntry method.
  5. Zip the data files using Archive.save method.
1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "Bzip2Compression_out.zip")) {
2    try (Archive archive = new Archive(new ArchiveEntrySettings(new Bzip2CompressionSettings()))) {
3        archive.createEntry("sample.txt", dataDir + "sample.txt");
4        archive.save(zipFile);
5    }
6} catch (IOException ignored) {
7    System.out.println(ex);
8}

Decompressing Archives

Decompress Archive having Single File

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressSingleFile_out.zip")) {
 2    try (Archive archive = new Archive(fs)) {
 3        int[] percentReady = new int[] {0};
 4        archive.getEntries().get(0).setExtractionProgressed(new Event<ProgressEventArgs>() {
 5            @Override
 6            public void invoke(Object sender, ProgressEventArgs progressEventArgs) {
 7                int percent = (int) ((100 * progressEventArgs.getProceededBytes())
 8                        / ((ArchiveEntry) sender).getUncompressedSize());
 9                if (percent > percentReady[0])
10                {
11                    System.out.println(percent + "% decompressed");
12                    percentReady[0] = percent;
13                }
14            }
15        });
16        archive.getEntries().get(0).extract(dataDir + "alice_extracted_out.txt");
17    }
18} catch (IOException ex) {
19    System.out.println(ex);
20}

Decompress Archive having Multiple Files

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressMultipleFiles_out.zip")) {
 2    StringBuilder sb = new StringBuilder("Entries are: ");
 3    int[] percentReady = new int[] {0};
 4    ArchiveLoadOptions options = new ArchiveLoadOptions();
 5    options.setEntryListed(new Event<EntryEventArgs>() {
 6        @Override
 7        public void invoke(Object sender, EntryEventArgs entryEventArgs) {
 8            sb.append(entryEventArgs.getEntry().getName()).append(", ");
 9        }
10    });
11    options.setEntryExtractionProgressed(new Event<ProgressEventArgs>() {
12        @Override
13        public void invoke(Object sender, ProgressEventArgs progressEventArgs) {
14            int percent = (int) ((100 * progressEventArgs.getProceededBytes())
15                    / ((ArchiveEntry) sender).getUncompressedSize());
16            if (percent > percentReady[0])
17            {
18                System.out.println(percent + "% compressed");
19                percentReady[0] = percent;
20            }
21        }
22    });
23    try (Archive archive = new Archive(fs, options)) {
24        System.out.println(sb.substring(0, sb.length() - 2));
25        try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_out.txt")) {
26            try (InputStream decompressed = archive.getEntries().get(0).open()) {
27                byte[] buffer = new byte[8192];
28                int bytesRead;
29                while (0 < (bytesRead = decompressed.read(buffer, 0, buffer.length))) {
30                    extracted.write(buffer, 0, bytesRead);
31                }
32                // Read from decompressed stream to extracting file.
33            }
34        }
35        percentReady[0] = 0;
36        archive.getEntries().get(1).extract(dataDir + "asyoulik_extracted_out.txt");
37    }
38} catch (IOException ex) {
39    System.out.println(ex);
40}

Extract Stored Archive without Compression

 1try (FileInputStream zipFile = new FileInputStream(dataDir + "StoreMultipleFilesWithoutCompression_out.zip")) {
 2    try (Archive archive = new Archive(zipFile )) {
 3        try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_store_out.txt")) {
 4            try (InputStream stored = archive.getEntries().get(0).open()) {
 5                byte[] buffer = new byte[8192];
 6                int bytesRead;
 7                while (0 < (bytesRead = stored.read(buffer, 0, buffer.length))) {
 8                    extracted.write(buffer, 0, bytesRead);
 9                }
10                // Read from stored stream to extracting file.
11            }
12        }
13        try (FileOutputStream extracted = new FileOutputStream(dataDir + "asyoulik_extracted_store_out.txt")) {
14            try (InputStream stored = archive.getEntries().get(1).open()) {
15                byte[] buffer = new byte[8192];
16                int bytesRead;
17                while (0 < (bytesRead = stored.read(buffer, 0, buffer.length))) {
18                    extracted.write(buffer, 0, bytesRead);
19                }
20                // Read from stored stream to extracting file.
21            }
22        }
23    }
24} catch (IOException ex) {
25    System.out.println(ex);
26}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.