Core Java

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";

    @Test
    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.write(text1.getBytes());
            zipOutputStream.closeEntry();

            zipOutputStream.putNextEntry(new ZipEntry(TEXT_ENTRY_2));
            zipOutputStream.write(text2.getBytes());
            zipOutputStream.closeEntry();
        }

        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)) {
                    Assert.assertEquals(text2,IOUtils.toString(zipInputStream));
                }
                zipInputStream.closeEntry();
            }
        } finally {
            Files.deleteIfExists(tempZip.toPath());
        }
    }
    
}
Reference: A Java gist on zip and unzip from our JCG partner Emmanouil Gkatziouras at the gkatzioura blog.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button