1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public static void copyTo(URL url, Path zipPath, String path) throws IOException {
final byte[] buffer = new byte[4096];
final Path tmpPath = Paths.get(zipPath.getParent().toString(), zipPath.getFileName().toString() + ".tmp");
final Set<String> folders = new HashSet<>();
try(ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(tmpPath));
ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipPath))) {
for(ZipEntry zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream.getNextEntry()) {
if ( zipEntry.getName().endsWith("/') ) {
folders.add(zipEntry.getName());
}
zipOutputStream.putNextEntry(zipEntry);
for(int read = zipInputStream.read(buffer); read!=-1; read= zipInputStream.read(buffer)) {
zipOutputStream.write(buffer, 0, read);
}
zipOutputStream.closeEntry();
}
if ( path.contains("/") ) {
final String targetFolder = path.substring(0, path.lastIndexOf("/")+1);
if ( !folders.contains(targetFolder) ) {
zipOutputStream.putNextEntry(new ZipEntry(targetFolder));
zipOutputStream.closeEntry();
}
}
final ZipEntry newZipEntry = new ZipEntry(path);
zipOutputStream.putNextEntry(newZipEntry);
try(InputStream urlStream = url.openStream()) { // attention, si le fichier distant est lui même un zip, il faudra utiliser un ZipInputStream intermédiaire
for(int read = urlStream.read(buffer); read!=-1; read = urlStream.read(buffer)) {
zipOutputStream.write(buffer, 0, read);
}
}
zipOutputStream.closeEntry();
}
Files.move(tmpPath, zipPath, StandardCopyOption.REPLACE_EXISTING);
} |
Partager