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());
}
}
}

view raw

gistfile1.txt

hosted with ❤ by GitHub

Advertisement

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.