It can be used to zip both a file or a Directory. Directory is ziped along with its subdirectory structure. Just Provide the proper source and run the code.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreateZip {
//function to zip a single file
//Parameters List :
//zipSrc : source file which to be ziped
//zipName : Give desire name to zip file
//destination folder where to create zip file
public void zipFile(File zipSrc,String zipName,String destFolder) {
System.out.println("zipFile :: "+zipSrc.getPath()+" "+zipName+" "+destFolder);
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFolder+File.separator+zipName));
FileInputStream fis = new FileInputStream(zipSrc);
ZipEntry zipEntry = new ZipEntry(zipSrc.getName());
zos.putNextEntry(zipEntry);
int bytes = 0;
byte[] buffer = new byte[2156];
bytes = fis.read(buffer);
while (bytes != -1) {
zos.write(buffer, 0, bytes);
bytes = fis.read(buffer);
}
fis.close();
zos.flush();
zos.close();
} catch (Exception e) {
System.out.println("Exception :: "+e);
}
}
//function to zip a folder containing multiple files
//Parameters List :
//zipSrc : source folder which to be ziped
//zipName : Give desire name to zip file
//destination folder where to create zip file
public void zipDirectory(File zipSrc,String zipName,String destFolder) {
System.out.println("zipDirectory :: "+zipSrc.getPath()+" "+zipName+" "+destFolder);
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFolder+File.separator+zipName));
zipDirectoryUtil(zipSrc.getPath(),zos,"");
zos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void zipDirectoryUtil(String directory,ZipOutputStream zos,String path) {
try {
File zipDir = new File(directory);
String[] allFiles = zipDir.list();
int bytes = 0;
byte[] buffer = new byte[2156];
for (String eachFile : allFiles) {
File file = new File(zipDir,eachFile);
if(file.isDirectory()) {
zipDirectoryUtil(file.getPath(),zos,path+file.getName()+File.separator);
continue;
}
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(path+file.getName());
zos.putNextEntry(zipEntry);
bytes = fis.read(buffer);
while (bytes != -1) {
zos.write(buffer, 0, bytes);
bytes = fis.read(buffer);
}
fis.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CreateZip obj = new CreateZip();
obj.zipFile(new File("C:\\MY\\Code\\Photo.jpg"),"img.zip","D:\\Test\\data");
obj.zipDirectory(new File("C:\\MY\\Code\\com"),"com.zip","D:\\Test\\data");
}
}