The task seems to run as required when using folders on my PC but I just can't seem to get it to verify. Depending on which order I either write the original files to the zip or copy over the new file I seem to get different requirements pass. Thank you.
package com.codegym.task.task31.task3105;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
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 {
String filePath = args[0];
String zipPath = args[1];
FileInputStream fis = new FileInputStream(zipPath);
ZipInputStream zis = new ZipInputStream(fis);
Map<String, byte[]> zipContents = getFiles(zis);
fis.close();
zis.close();
/*for (Map.Entry<String, byte[]> pair: zipContents.entrySet()){
System.out.println(pair.getKey() +" : " + Arrays.toString(pair.getValue()));
}*/
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
writeFiles(zipContents, zos);
writeFile(filePath, zos);
fos.close();
zos.close();
}
public static Map<String, byte[]> getFiles(ZipInputStream zis) throws IOException {
Map<String, byte[] > zipEntries = new HashMap<>();
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null){
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = zis.read(buffer)) > 0){
bos.write(buffer, 0, len);
}
zipEntries.put(zipEntry.getName(), bos.toByteArray());
bos.close();
}
return zipEntries;
}
public static void writeFiles(Map<String, byte[]> fileContents, ZipOutputStream zos) throws IOException {
for (Map.Entry<String, byte[]> pair: fileContents.entrySet()){
ZipEntry zipEntry = new ZipEntry(pair.getKey());
zos.putNextEntry(zipEntry);
zos.write(pair.getValue());
zos.closeEntry();
}
}
public static void writeFile(String filePath, ZipOutputStream zos) throws IOException {
zos.putNextEntry(new ZipEntry("new/" + Paths.get(filePath).getFileName()));
Files.copy(Paths.get(filePath), zos);
zos.closeEntry();
}
}