Discussion

Capgemini
Capgemini
CA
Capgemini
Posted: Mar 5, 2019
Last activity: Feb 27, 2020
Last activity: 27 Feb 2020 15:44 EST
Zip file in a directory
Below code will zip the files in a directory
// Make sure zip file is not written inside source directory
String zipFile = <Zip File Directory Path> + "/" + <Zip File Name> + ".zip";
String srcDir = <Directory path where files are located>;
try {
oLog.infoForced("Zip creation - Start");
// create byte buffer
byte[] buffer = new byte[1024];
java.io.FileOutputStream fos = new java.io.FileOutputStream(zipFile);
java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos);
java.io.File dir = new java.io.File(srcDir);
java.io.File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
java.io.FileInputStream fis = new java.io.FileInputStream(files[i]);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new java.util.zip.ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (Exception e) {
oLog.infoForced("Error creating zip file" + e.getMessage());
}
finally{
oLog.infoForced("Zip creation - End");
}