I had several working solutions and none of them was accepted. My solution right now looks almost as the one in the answer. The only difference I see, is that I am using map while CG is using their own object. So, what is wrong here? Is my solution wrong or it just does not follow the standards of CG?
package com.codegym.task.task31.task3105;
import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
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 {
Map<ZipEntry, byte[]> filesFromZip = filesMap(args[1]);
FileOutputStream fout = new FileOutputStream(args[1]);
ZipOutputStream zipOut = new ZipOutputStream(fout);
File newFile = new File(args[0]);
zipOut.putNextEntry(new ZipEntry("new/" + newFile.getName()));
Files.copy(newFile.toPath(), zipOut);
for (Map.Entry<ZipEntry, byte[]> entry: filesFromZip.entrySet()) {
if(!entry.getKey().getName().equals("new/" + newFile.getName())) toZip(entry.getKey(), entry.getValue(), newFile, zipOut);
}
zipOut.close();
}
public static Map<ZipEntry, byte[]> filesMap(String filePath) throws IOException {
Map<ZipEntry, byte[]> result = new HashMap<>();
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(filePath));
ZipEntry entry;
byte[] buffer = new byte[1024];
while ((entry = zipIn.getNextEntry()) != null) {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
int length = 0;
while ((length = zipIn.read(buffer)) > 0) {
byteOut.write(buffer, 0, length);
}
result.put(entry, byteOut.toByteArray());
byteOut.close();
}
return result;
}
public static void toZip(ZipEntry entry, byte[] bytes, File newFile, ZipOutputStream zipOut) throws IOException {
zipOut.putNextEntry(entry);
zipOut.write(bytes);
zipOut.closeEntry();
}
}