Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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(); } } } |
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.