How to make a zip file in java
This tutorial discusses the example code of creating a zip file in Java.
This tutorial discusses the example code of creating a zip file in Java.
Description:
In this example we will discuss about how to create zip file from the text file.
In the following code ZipOutputStream class from java.util.zip package is used. The ZipOutputStream class provides the methods to create zip file.
Code:
import java.io.*;
import java.util.zip.*;
import java.io.FileInputStream.*;
import java.util.zip.ZipOutputStream.*;
public class ZipDemo {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("unzipfile.txt");
BufferedInputStream zipin = new BufferedInputStream(fin);
FileOutputStream fout = new FileOutputStream("zipfile.zip");
BufferedOutputStream bout = new BufferedOutputStream(fout);
ZipOutputStream zipout = new ZipOutputStream(bout);
byte[] data = new byte[1000];
int count;
zipout.putNextEntry(new ZipEntry("zipfile.zip"));
while ((count = zipin.read(data, 0, 1000)) != -1) {
zipout.write(data, 0, count);
}
zipin.close();
zipout.close();
System.out.println("File SuccessFully converted In Zip Format");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
} |
Output:
When you compile and run this program it will create the zip (zipfile.zip ) of unzipfile.txt file