对于项目,我需要创建一个包含两个zip文件的zip。 我创建了一些方法,但是,生成的zip不正确。
考虑以下测试类:
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;
}
}
执行此操作时,文件p1.zip确实包含p.zip,但p.zip不可读。 有没有办法来解决这个问题? 或者是否有另一种拉链拉链方式?
答案 0 :(得分:0)
这是一种更简单的方法:
答案 1 :(得分:0)
直到我发现为什么这不起作用,它是使用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;
}
}
将结果拉链添加到另一个拉链时可以使用。