Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java zip file

farenda 2015-07-30 0

Problem:

Java has great support for Zip format and writing code in Java to zip/unzip file is really simple. Java 8 makes it even simpler. The following example shows how to zip and unzip file.

Solution:

In the following Java code we use java.util.zip package to zip content into a file and then unzip the file and read the content.

package com.farenda.java.io;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUnzipExample {

    public static void main(String[] args) throws IOException {
        String filename = "/tmp/sample-file.zip";

        createZipFile(filename, "This data will be zipped.");

        System.out.println("Unzipped content: " + readZipFile(filename));
    }

    private static void createZipFile(String filename, String content) throws IOException {
        // try-with-resources will close everything automatically
        try (Writer writer = createWriter(filename)) {
            System.out.println("Zipping: " + content);
            writer.write(content);
        }
    }

    private static Writer createWriter(String filename) throws IOException {
        OutputStream os = createOutputStream(filename);
        return new OutputStreamWriter(os);
    }

    private static OutputStream createOutputStream(String filename) throws IOException {
        OutputStream fos = Files.newOutputStream(Paths.get(filename));
        ZipOutputStream zos = new ZipOutputStream(fos);
        // Sample zip entry, here: a filename
        ZipEntry entry = new ZipEntry("sample-file.txt");
        zos.putNextEntry(entry);
        return new BufferedOutputStream(zos);
    }

    private static String readZipFile(String filename) throws IOException {
        // try-with-resources will close everything automatically
        try (BufferedReader reader = createReader(filename)) {
            // use Java 8 Streams to load all lines:
            return reader.lines().collect(Collectors.joining());
        }
    }

    private static BufferedReader createReader(String filename) throws IOException {
        InputStream zis = createInputStream(filename);
        return new BufferedReader(new InputStreamReader(zis));
    }

    private static InputStream createInputStream(String filename) throws IOException {
        InputStream is = Files.newInputStream(Paths.get(filename));
        ZipInputStream zis = new ZipInputStream(is);
        // for many entries read one by one
        ZipEntry entry = zis.getNextEntry();
        System.out.println("Zip entry: " + entry.getName());
        return zis;
    }
}

Notice how we use try-with-resources from Java 7 to close all streams and prevent resource leakage. Also we use Java 8 Streams to read all lines (1 in this case) from unzipped input stream.

Also note how code has been split to small, highly cohesive, methods that do only one thing.

Running the example shows that zipping and unzipping works as expected:

Zipping: This data will be zipped.
Zip entry: sample-file.txt
Unzipped content: This data will be zipped.
Share with the World!
Categories Java Tags java-util
Previous: Java Collection min/max value
Next: Java Collections nCopies

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored