【问题标题】:zipping files in java memory produces a zip file but the files inside are empty在java内存中压缩文件会产生一个zip文件但里面的文件是空的
【发布时间】:2020-11-20 04:07:33
【问题描述】:

我正在尝试用 Java 压缩多个文件以在我的 jar 中使用。 2 个文件是图像,1 个是 HTML 临时文件。压缩这些文件后,当我尝试查看 zip 文件的内容时,所有 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();
    }

【问题讨论】:

    标签: java maven jar zip


    【解决方案1】:

    您忘记写入字节。 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();
    

    【讨论】:

    • 嗨,这非常适合我的 html 文件。我的图像仍然是空的。知道为什么吗??
    • 你还有问题吗。您确定正确加载图像吗?因为您提到了文件名而不是路径并指定了 Non-Null。也许您的图像未正确加载,但文件仍然不为空。请指定路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多