diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java new file mode 100644 index 0000000000..d0b4274731 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -0,0 +1,31 @@ +package com.baeldung.unzip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class UnzipFile { + public static void main(String[] args) throws FileNotFoundException, IOException { + String fileZip = "/opt/zipped/cities.zip"; + byte[] buffer = new byte[1024]; + ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); + ZipEntry zipEntry = zis.getNextEntry(); + while(zipEntry != null){ + String fileName = zipEntry.getName(); + File newFile = new File("/opt/unzipped/" + fileName); + FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); + zipEntry = zis.getNextEntry(); + } + zis.closeEntry(); + zis.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java new file mode 100644 index 0000000000..dccd3f2347 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java @@ -0,0 +1,29 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipFile { + public static void main(String[] args) throws FileNotFoundException, IOException { + String sourceFile = "/opt/photos/photo.png"; + FileOutputStream fos = new FileOutputStream("/opt/zipped/cities.zip"); + ZipOutputStream zipOut = new ZipOutputStream(fos); + File fileToZip = new File(sourceFile); + FileInputStream fis = new FileInputStream(fileToZip); + ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zipOut.putNextEntry(zipEntry); + byte[] bytes = new byte[1024]; + int length; + while((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + zipOut.close(); + fis.close(); + fos.close(); + } +} \ No newline at end of file