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

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

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

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();
    }
bqjvbblv

bqjvbblv1#

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

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();

相关问题