A Java gist on zip and unzip

Compressing is one of the major actions that can be issued in our code when it comes to writing files. Thus I find a simple java snippet on zip and unzip essential and  has to be easily accessed.

This gist is in plain java and stores two files in a zip. Once done the produced zip is open and its contents are evaluated.

import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
* Created by gkatzioura on 4/12/17.
public class ArhivingTest {
private static final String TEXT_ENTRY_1 = "text1.txt";
private static final String TEXT_ENTRY_2 = "text2.txt";
public void zipAndUnzip() throws IOException {
String text1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ";
String text2 = "eiusmod tempor incididunt ut labore et dolore magna aliqua. ";
File tempZip = File.createTempFile("temp",".zip");
try(OutputStream outputStream = new FileOutputStream(tempZip);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
zipOutputStream.putNextEntry(new ZipEntry(TEXT_ENTRY_1));
zipOutputStream.putNextEntry(new ZipEntry(TEXT_ENTRY_2));
try(InputStream inputStream = new FileInputStream(tempZip);
ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry entry = null;
while ((entry=zipInputStream.getNextEntry())!=null) {
if(entry.getName().equals(TEXT_ENTRY_1)) {
Assert.assertEquals(text1, IOUtils.toString(zipInputStream));
if(entry.getName().equals(TEXT_ENTRY_2)) {
} finally {

view raw


hosted with ❤ by GitHub


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.