For a project I need to create a zip that contains two zip files. I created some methods to do that, however, the resulting zip is not correct.
Consider the following test class:
package nl.test;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.Test;
public class ZipTest {
@Test
public void test() throws IOException {
Path p = Paths.get("input.txt");
try (BufferedWriter writer = Files.newBufferedWriter(p)) {
writer.write("text to compress");
}
Path p1 = createZipFile("p.zip", p);
createZipFile("p1.zip", p1);
}
private Path createZipFile(String zipName, Path p) {
try {
OutputStream fos = Files.newOutputStream(Paths.get(zipName));
ZipOutputStream zos = new ZipOutputStream(fos);
OutputStream bos = new BufferedOutputStream(zos);
try (Writer writer = new OutputStreamWriter(bos)) {
zos.putNextEntry(new ZipEntry(p.toString()));
writer.write(new String(Files.readAllBytes(p)));
writer.flush();
}
return Paths.get(zipName);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
When executing this, the file p1.zip does indeed contain a p.zip, however, that p.zip is unreadable. Is there a way to fix this? Or is there another way to place a zip in a zip?
Here's a simpler way:
Until I find out why this is not working, it is solved using zip4j:
package nl.test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class ZipTest2 {
@Test
public void test() throws IOException {
Path p = Paths.get("input.txt");
try (BufferedWriter writer = Files.newBufferedWriter(p)) {
writer.write("text to compress");
}
Path p1 = createZipFile("p1.zip", p);
createZipFile("p2.zip", p1);
}
private Path createZipFile(String compressedFile, Path inputPath) {
try {
ZipFile zipFile = new ZipFile(compressedFile);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);
zipFile.addFile(inputPath.toFile(), parameters);
return Paths.get(compressedFile);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This works when adding a resulting zip to another zip.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.