Skip to content

Instantly share code, notes, and snippets.

@soberich
Created May 4, 2020 20:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soberich/eb3b98e5b5c91b56fe711f4782ccf119 to your computer and use it in GitHub Desktop.
Save soberich/eb3b98e5b5c91b56fe711f4782ccf119 to your computer and use it in GitHub Desktop.
Java 7 NIO2 Download ZIP from URL and Unzip on the fly with Channels
package com.example;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
public class ZipUtils {
public static void unzip(final URL url, final Path decryptTo) {
try (ZipInputStream zipInputStream = new ZipInputStream(Channels.newInputStream(Channels.newChannel(url.openStream())))) {
for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream.getNextEntry()) {
Path toPath = decryptTo.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectory(toPath);
} else try (FileChannel fileChannel = FileChannel.open(toPath, WRITE, CREATE/*, DELETE_ON_CLOSE*/)) {
fileChannel.transferFrom(Channels.newChannel(zipInputStream), 0, Long.MAX_VALUE);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment