Zip File Creation In Java Example
Chapter:
ZIP
Last Updated:
23-06-2016 16:43:33 UTC
Program:
/* ............... START ............... */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class JavaZipFileExample {
public static void main(String[] args) {
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("scan.log");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("C:\\scan.log");
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
// remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/* ............... END ............... */
Output
Creates MyFile.zip in C Drive.
Notes:
-
Java comes with java.util.zip library to perform data compression in ZIP format.
- FileOutputStream to write to the file with the specified name, that is the zipFile.
- ZipOutputStream from the FileOutputStream, that is an output stream filter for writing files in the ZIP file format.
Tags
Zip File, Java