[英]zipping files in java memory produces a zip file but the files inside are empty
I am trying to zip multiple files in Java to be used in my jar.我正在尝试用 Java 压缩多个文件以在我的 jar 中使用。 2 files are images and 1 is an HTML temp file.
2 个文件是图像,1 个是 HTML 临时文件。 Upon zipping these files, when I try to see the contents of the zip file, all 3 files have become empty.
压缩这些文件后,当我尝试查看 zip 文件的内容时,所有 3 个文件都变空了。 There is no error being thrown as the files are in the zip but they are empty for some reason.
没有错误被抛出,因为文件在 zip 中,但由于某种原因它们是空的。 I need to save my zip file in memory.
我需要将我的 zip 文件保存在内存中。
Here is my zip code.这是我的邮政编码。
public static File zipPdf(File data, File cover) throws IOException {
ArrayList<ByteArrayOutputStream> zips = new ArrayList<>();
ClassLoader loader = RunningPDF.class.getClassLoader();
File image = new File(Objects.requireNonNull(loader.getResource("chekklogo.png")).getFile());
File man = new File(Objects.requireNonNull(loader.getResource("manlogo.jpg")).getFile());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry(data.getName());
zos.putNextEntry(entry);
ZipEntry entry2 = new ZipEntry(image.getName());
zos.putNextEntry(entry2);
ZipEntry entry3 = new ZipEntry(man.getName());
zos.putNextEntry(entry3);
} catch(IOException ioe) {
ioe.printStackTrace();
}
You forget to write the bytes.你忘记写字节了。 The putNextEntry just adds an entry.
putNextEntry 只是添加了一个条目。 You need to explicitly write the bytes.
您需要明确写入字节。 Go with the following
跟着下面走
File file = new File(filePath);
String zipFileName = file.getName().concat(".zip");
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry(file.getName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
zos.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.