diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java index 140d809d44..a18663f544 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -16,31 +16,42 @@ public class UnzipFile { ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { final File newFile = newFile(destDir, zipEntry); - final FileOutputStream fos = new FileOutputStream(newFile); - int len; - while ((len = zis.read(buffer)) > 0) { - fos.write(buffer, 0, len); + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory " + newFile); + } + } else { + File parent = newFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory " + parent); + } + + final FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); } - fos.close(); zipEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } - + /** * @see https://snyk.io/research/zip-slip-vulnerability */ public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { File destFile = new File(destinationDir, zipEntry.getName()); - + String destDirPath = destinationDir.getCanonicalPath(); String destFilePath = destFile.getCanonicalPath(); - + if (!destFilePath.startsWith(destDirPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); } - + return destFile; } } \ No newline at end of file