JAVA-5735: Appending a new File to a ZIP file (#13044)

This commit is contained in:
Harry9656 2022-11-22 08:44:18 +01:00 committed by GitHub
parent 66f1799b72
commit 66fb7ea877
3 changed files with 36 additions and 2 deletions

View File

@ -0,0 +1,29 @@
package com.baeldung.zip;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static java.util.stream.Collectors.toList;
public class ZipAppendFile {
public static void main(final String[] args) throws IOException {
ZipMultipleFiles.main(args);
String file3 = ZipAppendFile.class.getClassLoader().getResource("zipTest/file3.txt").getPath();
Map<String, String> env = new HashMap<>();
env.put("create", "true");
Path path = Paths.get(Paths.get(file3).getParent() + "/compressed.zip");
URI uri = URI.create("jar:" + path.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
Path nf = fs.getPath("newFile3.txt");
Files.write(nf, Files.readAllBytes(Paths.get(file3)), StandardOpenOption.CREATE);
}
}
}

View File

@ -4,6 +4,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
@ -11,8 +12,11 @@ import java.util.zip.ZipOutputStream;
public class ZipMultipleFiles {
public static void main(final String[] args) throws IOException {
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
String file1 = ZipAppendFile.class.getClassLoader().getResource("zipTest/test1.txt").getPath();
String file2 = ZipAppendFile.class.getClassLoader().getResource("zipTest/test2.txt").getPath();
final List<String> srcFiles = Arrays.asList(file1, file2);
final FileOutputStream fos =
new FileOutputStream(Paths.get(file1).getParent().toAbsolutePath() + "/compressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
for (final String srcFile : srcFiles) {
final File fileToZip = new File(srcFile);

View File

@ -0,0 +1 @@
Test3.txt