My first method which worked (I think so :D) but not gave me green light.
public void removeFiles(List<Path> pathList) throws Exception {
if (!Files.isRegularFile(zipFile))
throw new NoSuchZipFileException();
Path temp = Files.createTempFile(null, null);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(temp));
ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
boolean toBeDeleted = false;
for (Path pathToRemove : pathList) {
if (zipEntry.getName().equals(pathToRemove.getFileName().toString())) {
ConsoleHelper.writeMessage("We have to remove path: " + zipEntry.getName());
toBeDeleted = true;
break;
}
}
if (!toBeDeleted) {
zipOutputStream.putNextEntry(zipEntry);
copyData(zipInputStream, zipOutputStream);
zipOutputStream.closeEntry();
}
zipEntry = zipInputStream.getNextEntry();
}
}
// Replace the original archive file with the temporary file
Files.move(temp, zipFile, StandardCopyOption.REPLACE_EXISTING);
}
Method which gave me validation:
public void removeFiles(List<Path> pathList) throws Exception {
if (!Files.isRegularFile(zipFile))
throw new NoSuchZipFileException();
Path temp = Files.createTempFile(null, null);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(temp));
ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
if (pathList.contains(Paths.get(zipEntry.getName()))) {
ConsoleHelper.writeMessage("We have to remove path: " + zipEntry.getName());
} else {
zipOutputStream.putNextEntry(zipEntry);
copyData(zipInputStream, zipOutputStream);
zipOutputStream.closeEntry();
}
zipEntry = zipInputStream.getNextEntry();
}
}
// Replace the original archive file with the temporary file
Files.move(temp, zipFile, StandardCopyOption.REPLACE_EXISTING);
}
I was inspired to code my "first" method from this https://stackoverflow.com/questions/5244963/delete-files-from-a-zip-archive-without-decompressing-in-java-or-maybe-python
I'm curious whether Big Validator was severe, or maybe I overlooked something and that method is incorrect.
It is any difference except performance? I see it could be trouble with big zip file.