public static void compressToZip(String sourceFilePath, String zipFilePath, String zipFilename) {
File sourceFile = new File(sourceFilePath);
File targetFile = new File(zipFilePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetFile + File.separator + zipFilename)))) {
writeZip(sourceFile, "", zipOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.isDirectory()) {
File[] files = file.listFiles();
parentPath += file.getName() + File.separator;
for (File file1 : files) {
writeZip(file1, parentPath, zos);
}
} else {
BufferedInputStream bufferedInputStream = null;
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(zipEntry);
byte[] buff = new byte[1024];
int len;
while ((len = bufferedInputStream.read(buff, 0, buff.length)) != -1) {
zos.write(buff, 0, buff.length);
zos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}