Last active
April 17, 2025 17:16
-
-
Save soberich/eb3b98e5b5c91b56fe711f4782ccf119 to your computer and use it in GitHub Desktop.
Java 7 NIO2 Download ZIP from URL and Unzip, select/filter entries [and decrypt! if needed] **on the fly** with Channels (WITHOUT CREATING INTIMIDATE COPY OF DATA BYTES)
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
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