Skip to content

Instantly share code, notes, and snippets.

@steventzeng-base
Created March 25, 2016 07:32
Show Gist options
  • Save steventzeng-base/4ca4b0aa15ecdd6db097 to your computer and use it in GitHub Desktop.
Save steventzeng-base/4ca4b0aa15ecdd6db097 to your computer and use it in GitHub Desktop.
Java 7 NIO2 Unzip Code
public class ZipUtils {
private static final Logger LOGGER = Logger.getLogger(ZipUtils.class.getName());
public static void unzip(final Path zipFile, final Path decryptTo) {
try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
LOGGER.log(Level.INFO, "entry name = {0}", entry.getName());
final Path toPath = decryptTo.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectory(toPath);
} else {
Files.copy(zipInputStream, toPath);
}
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
@JavoGithub
Copy link

Very neat sir! Thanks for sharing.

@breymerrobles
Copy link

good piece of code working very well, thanks a lot for sharing

@AntonyGlim
Copy link

Thanks for sharing.

@soberich
Copy link

soberich commented May 4, 2020

Download from internet, and unpack on the fly with NIO channels.
Works as charm!

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);
                }
            }
        }
    }
}

https://gist.github.com/soberich/eb3b98e5b5c91b56fe711f4782ccf119

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment