Created
March 25, 2016 07:32
-
-
Save steventzeng-base/4ca4b0aa15ecdd6db097 to your computer and use it in GitHub Desktop.
Java 7 NIO2 Unzip Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
good piece of code working very well, thanks a lot for sharing
Thanks for sharing.
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
Very neat sir! Thanks for sharing.