Today I am going to explain you how we can create zip file in Java. Java comes with java.util.zip library which helps in creating zip file in java, to create zip file you have to include java.util.zip library in your project, read the below article to know how we do it.
Step1: you have to create a program with file name CreatingZip and paste the below code before running this code you have to keep your file hello.txt in your D drive, you can change the file name according to you in the below program.
package creatingzip;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreatingZip
{
public static void main( String[] args )
{
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream("D:\\Hello.zip");
ZipOutputStream zostream = new ZipOutputStream(fos);
ZipEntry zipentry= new ZipEntry("hello.txt");
zostream.putNextEntry(zipentry);
FileInputStream in = new FileInputStream("D:\\hello.txt");
int len;
while ((len = in.read(buffer)) > 0) {
zostream.write(buffer, 0, len);
}
in.close();
zostream.closeEntry();
//remember close it
zostream.close();
System.out.println("Zip file created successfully");
}catch(IOException err){
System.out.println("Sorry an IOException occured "+err);
}
}
}
Output:
Zip file created successfully
BUILD SUCCESSFUL (total time: 1 second)
5 Comments
Thanks for this code :)
ReplyDeleteThanks bro
DeleteThanks for the code, but using this code all files are listed in a zip folder but i want to list a folder which contain all my files in a zip folder, i want to say directory structure should be "Zip Folder>>My Folder>>All Files"
ReplyDeletemodify your line as shown below
DeleteZipEntry ze= new ZipEntry("My Files\\hello.txt");
Its works, thanks sir for your reply
Delete