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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |