Skip to content

Instantly share code, notes, and snippets.

@thekalinga
Created August 28, 2019 13:02
Show Gist options
  • Save thekalinga/14417d0838feb6b0a8ae23119774d433 to your computer and use it in GitHub Desktop.
Save thekalinga/14417d0838feb6b0a8ae23119774d433 to your computer and use it in GitHub Desktop.
Zip directory recursively in java8
public static void zip(Path sourceDirPath, Path zipFilePath) throws IOException {
//@formatter:off
createFile(zipFilePath, DEFAULT_FILE_ATTRS);
try (ZipOutputStream zos = new ZipOutputStream(newOutputStream(zipFilePath)); Stream<Path> paths = Files.walk(sourceDirPath)) {
paths.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
log.error("Failed while zipping", e);
}
});
}
//@formatter:on
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment