public void addFiles(List<Path> absolutePathList) throws Exception{
if (!Files.isRegularFile(zipFile)) {
throw new WrongZipFileException();
}
Path tempZipFile = Files.createTempFile(null, null);
List<Path> localListPath = new ArrayList<>();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(tempZipFile));
ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry zipEntry;;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
copyData(zipInputStream, zipOutputStream);
zipInputStream.closeEntry();
zipOutputStream.closeEntry();
localListPath.add(Paths.get(zipEntry.getName()));
for (Path absolutePath: absolutePathList
) {
if (Files.notExists(absolutePath)) {
throw new PathIsNotFoundException();
}
if (!localListPath.contains(absolutePath)) {
addNewZipEntry(zipOutputStream, absolutePath.getParent(), absolutePath.getFileName());
ConsoleHelper.writeMessage(String.format("Добавили файл ", absolutePath.toString()));
} else {
ConsoleHelper.writeMessage(String.format("Такой файл уже есть ", absolutePath.toString()));
}
}
}
}
Files.move(tempZipFile, zipFile, StandardCopyOption.REPLACE_EXISTING);
}package com.javarush.task.task31.task3110;
import com.javarush.task.task31.task3110.exception.WrongZipFileException;
import java.io.IOException;
public class Archiver {
public static void main(String[] args) throws IOException {
Operation operation = null;
do {
try {
operation = askOperation();
CommandExecutor.execute(operation);
} catch (WrongZipFileException e) {
ConsoleHelper.writeMessage("Вы не выбрали файл архива или выбрали неверный файл.");
} catch (Exception e) {
ConsoleHelper.writeMessage("Произошла ошибка. Проверьте введенные данные.");
}
} while (operation != Operation.EXIT);
}
public static Operation askOperation() throws IOException {
ConsoleHelper.writeMessage("");
ConsoleHelper.writeMessage("Выберите операцию:");
ConsoleHelper.writeMessage(String.format("\t %d - упаковать файлы в архив", Operation.CREATE.ordinal()));
ConsoleHelper.writeMessage(String.format("\t %d - добавить файл в архив", Operation.ADD.ordinal()));
ConsoleHelper.writeMessage(String.format("\t %d - удалить файл из архива", Operation.REMOVE.ordinal()));
ConsoleHelper.writeMessage(String.format("\t %d - распаковать архив", Operation.EXTRACT.ordinal()));
ConsoleHelper.writeMessage(String.format("\t %d - просмотреть содержимое архива", Operation.CONTENT.ordinal()));
ConsoleHelper.writeMessage(String.format("\t %d - выход", Operation.EXIT.ordinal()));
return Operation.values()[ConsoleHelper.readInt()];
}
}