zip and unzip
This commit is contained in:
parent
f8258e9221
commit
04f794a255
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue