zipping文件生成一个zip文件,但是里面的文件是空的

h4cxqtbf  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(417)

我正在尝试用java压缩多个文件,以便在jar中使用。2个文件是图像,1个是html临时文件。在压缩这些文件时,当我试图查看压缩文件的内容时,所有3个文件都变空了。由于文件在zip中,但由于某些原因它们是空的,因此不会抛出任何错误。我需要把我的zip文件保存在内存中。
这是我的邮政编码。

  1. public static File zipPdf(File data, File cover) throws IOException {
  2. ArrayList<ByteArrayOutputStream> zips = new ArrayList<>();
  3. ClassLoader loader = RunningPDF.class.getClassLoader();
  4. File image = new File(Objects.requireNonNull(loader.getResource("chekklogo.png")).getFile());
  5. File man = new File(Objects.requireNonNull(loader.getResource("manlogo.jpg")).getFile());
  6. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  7. try(ZipOutputStream zos = new ZipOutputStream(baos)) {
  8. ZipEntry entry = new ZipEntry(data.getName());
  9. zos.putNextEntry(entry);
  10. ZipEntry entry2 = new ZipEntry(image.getName());
  11. zos.putNextEntry(entry2);
  12. ZipEntry entry3 = new ZipEntry(man.getName());
  13. zos.putNextEntry(entry3);
  14. } catch(IOException ioe) {
  15. ioe.printStackTrace();
  16. }
bqjvbblv

bqjvbblv1#

你忘了写字节。putnextentry只添加了一个条目。您需要显式地写入字节。遵循以下步骤

  1. File file = new File(filePath);
  2. String zipFileName = file.getName().concat(".zip");
  3. FileOutputStream fos = new FileOutputStream(zipFileName);
  4. ZipOutputStream zos = new ZipOutputStream(fos);
  5. zos.putNextEntry(new ZipEntry(file.getName()));
  6. byte[] bytes = Files.readAllBytes(Paths.get(filePath));
  7. zos.write(bytes, 0, bytes.length);
  8. zos.closeEntry();
  9. zos.close();

相关问题