Skip to content

Commit 04f794a

Browse files
committed
zip and unzip
1 parent f8258e9 commit 04f794a

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)