Skip to content

Instantly share code, notes, and snippets.

@zhmz1326
Created March 29, 2017 09:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhmz1326/d2787af7801b0efaeb522a2c3979c599 to your computer and use it in GitHub Desktop.
Save zhmz1326/d2787af7801b0efaeb522a2c3979c599 to your computer and use it in GitHub Desktop.
Compress a directory to a zip stream using commons-compress and java
public static void compressZipfile(String sourceDir, OutputStream os) throws IOException {
ZipOutputStream zos = new ZipOutputStream(os);
compressDirectoryToZipfile(sourceDir, sourceDir, zos);
IOUtils.closeQuietly(zos);
}
private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException {
File[] fileList = new File(sourceDir).listFiles();
if (fileList.length == 0) { // empty directory / empty folder
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + "/");
out.putNextEntry(entry);
out.closeEntry();
} else {
for (File file : fileList) {
if (file.isDirectory()) {
compressDirectoryToZipfile(rootDir, sourceDir + File.separator + file.getName(), out);
} else {
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + File.separator + file.getName());
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(sourceDir + File.separator + file.getName());
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment