File tree Expand file tree Collapse file tree
core-java-8/src/main/java/com/baeldung Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .unzip ;
2+
3+ import java .io .File ;
4+ import java .io .FileInputStream ;
5+ import java .io .FileNotFoundException ;
6+ import java .io .FileOutputStream ;
7+ import java .io .IOException ;
8+ import java .util .zip .ZipEntry ;
9+ import java .util .zip .ZipInputStream ;
10+
11+ public class UnzipFile {
12+ public static void main (String [] args ) throws FileNotFoundException , IOException {
13+ String fileZip = "/opt/zipped/cities.zip" ;
14+ byte [] buffer = new byte [1024 ];
15+ ZipInputStream zis = new ZipInputStream (new FileInputStream (fileZip ));
16+ ZipEntry zipEntry = zis .getNextEntry ();
17+ while (zipEntry != null ){
18+ String fileName = zipEntry .getName ();
19+ File newFile = new File ("/opt/unzipped/" + fileName );
20+ FileOutputStream fos = new FileOutputStream (newFile );
21+ int len ;
22+ while ((len = zis .read (buffer )) > 0 ) {
23+ fos .write (buffer , 0 , len );
24+ }
25+ fos .close ();
26+ zipEntry = zis .getNextEntry ();
27+ }
28+ zis .closeEntry ();
29+ zis .close ();
30+ }
31+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .zip ;
2+
3+ import java .io .File ;
4+ import java .io .FileInputStream ;
5+ import java .io .FileNotFoundException ;
6+ import java .io .FileOutputStream ;
7+ import java .io .IOException ;
8+ import java .util .zip .ZipEntry ;
9+ import java .util .zip .ZipOutputStream ;
10+
11+ public class ZipFile {
12+ public static void main (String [] args ) throws FileNotFoundException , IOException {
13+ String sourceFile = "/opt/photos/photo.png" ;
14+ FileOutputStream fos = new FileOutputStream ("/opt/zipped/cities.zip" );
15+ ZipOutputStream zipOut = new ZipOutputStream (fos );
16+ File fileToZip = new File (sourceFile );
17+ FileInputStream fis = new FileInputStream (fileToZip );
18+ ZipEntry zipEntry = new ZipEntry (fileToZip .getName ());
19+ zipOut .putNextEntry (zipEntry );
20+ byte [] bytes = new byte [1024 ];
21+ int length ;
22+ while ((length = fis .read (bytes )) >= 0 ) {
23+ zipOut .write (bytes , 0 , length );
24+ }
25+ zipOut .close ();
26+ fis .close ();
27+ fos .close ();
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments