This Post about how we compress file in Java.
For this java provide java.util.zip API
Here We read file kodemaker.txt and write file into kodemaker.zip.
Zip Entry is used to add file entry kodemaker.txt in zip file.
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 39 40 41 42 43 44 45 | package com.kodemaker; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class JavaFileCompressor { public static void main(String[] args) { byte[] arrayBuffer = new byte[1024]; int length; try { // Create output file kodemaker.zip FileOutputStream fileOutputStream = new FileOutputStream("Kodemaker.zip"); //Stream for writing files in the ZIP file format ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); // to file entry in zip ZipEntry zipEntry = new ZipEntry("Kodemaker.txt"); zipOutputStream.putNextEntry(zipEntry); // Create output file kodemaker.txt FileInputStream fileInputStream = new FileInputStream("Kodemaker.txt"); //read kodemaker.txt and write into kodemaker.zip while ((length = fileInputStream.read(arrayBuffer)) > 0) { zipOutputStream.write(arrayBuffer, 0, length); } //close all stream fileInputStream.close(); zipOutputStream.closeEntry(); zipOutputStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } } |
No comments:
Post a Comment