Created
May 4, 2020 20:46
-
-
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
This file contains 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
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