簡體   English   中英

壓縮java內存中的文件會產生一個zip文件,但里面的文件是空的

[英]zipping files in java memory produces a zip file but the files inside are empty

我正在嘗試用 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();
    }

你忘記寫字節了。 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM