I don't get it. I look to some other solutions. It is more or less doing the same thing, but just saving the content somewhere else first, but it is kind of the same at the end, no?
Also, why don't we simply skip the entries to add the new one?
package com.codegym.task.task31.task3105;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/*
Adding a file to an archive
*/
public class Solution {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream(args[1]);
ZipInputStream inputZip = new ZipInputStream(input);
FileOutputStream output = new FileOutputStream(args[1]);
ZipOutputStream outputZip = new ZipOutputStream(output);
ZipEntry entry;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((entry = inputZip.getNextEntry()) != null) {
while ((len = inputZip.read(buffer)) > 0) {
stream.write(buffer, 0, len);
}
outputZip.putNextEntry(entry);
outputZip.write(stream.toByteArray());
}
inputZip.close();
File file = new File(args[0]);
outputZip.putNextEntry(new ZipEntry("new/" + file.getName()));
Files.copy(file.toPath(), outputZip);
outputZip.close();
}
}