public class Solution {
public static void main(String[] args) throws IOException {
String filename = args[0];
String zipPath = args[1];
String resultFileName = "new" + File.separator + Paths.get(filename).getFileName().toString();
Map<String, ByteArrayOutputStream> tmp = new HashMap<>();
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipPath));
while (zis.available() > 0) {
ZipEntry ze = zis.getNextEntry();
if (ze.getName().equals(resultFileName))
continue;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
tmp.put(ze.getName(), baos);
zis.closeEntry();
}
zis.close();
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
for (Map.Entry<String, ByteArrayOutputStream> entry : tmp.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey()));
zos.write(entry.getValue().toByteArray());
zos.closeEntry();
}
zos.putNextEntry(new ZipEntry(resultFileName));
Files.copy(Paths.get(filename), zos);
zos.closeEntry();
zos.close();
}
}
package com.javarush.task.task31.task3105;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/*
Добавление файла в архив
*/
public class Solution {
public static void main(String[] args) throws IOException {
String filename = args[0];
String zipPath = args[1];
String resultFileName = "new" + File.separator + Paths.get(filename).getFileName().toString();
Map<String, ByteArrayOutputStream> tmp = new HashMap<>();
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipPath));
while (zis.available() > 0) {
ZipEntry ze = zis.getNextEntry();
if (ze.getName().equals(resultFileName))
continue;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
tmp.put(ze.getName(), baos);
zis.closeEntry();
}
zis.close();
Files.deleteIfExists(Paths.get(zipPath));
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
for (Map.Entry<String, ByteArrayOutputStream> entry : tmp.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey()));
zos.write(entry.getValue().toByteArray());
zos.closeEntry();
}
zos.putNextEntry(new ZipEntry(resultFileName));
Files.copy(Paths.get(filename), zos);
zos.closeEntry();
zos.close();
}
}