Don't know what's wrong with my solution, it run just as the condition on my computer, but still cannot pass the test. It seems that some kind of exception occured, but iI cannot figure it out...
package com.codegym.task.task31.task3105;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;
/*
Adding a file to an archive
*/
public class Solution {
public static void main(String[] args) throws IOException {
if (args.length>0){
String fileToBeAdded = args[0];
String name = fileToBeAdded.substring(fileToBeAdded.lastIndexOf("/") + 1);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(args[1]));
Map<ZipEntry,Path> content = new LinkedHashMap<>();
ZipEntry entry;
while ((entry=zipInputStream.getNextEntry())!=null){
//System.out.println(entry);
if (!entry.getName().equals("new/"+name))
{
if (!entry.isDirectory() && (entry.getSize() > 0))
{
/* byte[] bytes = new byte[(int) entry.getSize()];
System.out.println(entry.getName());
zipInputStream.read(bytes);*/
Path temp = Files.createTempFile("temp","");
Files.copy(zipInputStream,temp,StandardCopyOption.REPLACE_EXISTING);
content.put(entry,temp);
}
else {
content.put(entry,null);
}
}
}
zipInputStream.close();
Path added = Paths.get(fileToBeAdded);
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(args[1]));
zipOutputStream.putNextEntry(new ZipEntry("new/" + name));
Files.copy(added,zipOutputStream);
content.forEach((zipEntry, path) -> {
try
{
//System.out.println(zipEntry);
zipOutputStream.putNextEntry(zipEntry);
if (path != null)
{
Files.copy(path,zipOutputStream);
}
}
catch (IOException e)
{
e.printStackTrace();
}
});
zipOutputStream.close();
}
}
}