簡體   English   中英

將文件復制到Java中的雙重存檔(另一個zip文件中的一個zip文件)中

[英]Copy a file into a double archive in Java (a zip file which is in another zip file)

我有一個耳朵檔案,“ archive.ear”。 該檔案文件包含一個戰爭文件“ archive.war”。 在此文件中,我想用磁盤上存在的新文件替換“ /myFile.properties”文件。

新文件的內容保存在名為“ file”的java.io.File對象中。 我將存檔中“ /myFile.properties”的輸出流保存在java.io.OutputStream對象中。 之后,我嘗試使用

org.apache.commons.io.FileUtils.copy(File input, OutputStream output)

當前代碼是:

// Java method from extracting the output stream
public OutputStream getOutputStream(OutputStream out, String entry) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(out);
    ZipEntry zipEntry = new ZipEntry(entry);
    while (zipEntry != null) {
        if (zipEntry.toString().equals(entry)) {
            return zos;
        }
    }
    throw new IllegalStateException("No entry '" + entry + "' found");
}

// copy the file content to output stream
// extract output stream "archive.war" from "archive.ear"
OutputStream warOs = zu.getOutputStream(new FileOutputStream("archive.ear"), "archive.war");

// extract output stream "<path>/myFile.properties" from "archive.war"
OutputStream myFileOutput = zu.getOutputStream(warOs, "<path>/myFile.properties" );  

FileUtils.copyFile(file, myFileOutput);

我還嘗試使用由copyFile()插入:

myFileOutput.write(getBytesFromFile(file));

方法“ getBytesFromFile()”從文件對象返回字節數組。

當我打開戰爭存檔時,我希望“ myFile.properties”具有新的內容,該內容位於Java對象“ file”中。 該文件具有正確的內容。 結果是ZipException:

Exception in thread "main" java.util.zip.ZipException: no current ZIP entry
       at java.util.zip.ZipOutputStream.write(Unknown Source)
       at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2315)
       at org.apache.commons.io.IOUtils.copy(IOUtils.java:2270)
       at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2291)
       at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1094)
       at main.Main.main(Main.java:69)

您不能(輕松)使用Java操作現有的zip文件。 您將必須以回旋方式進行操作。

  1. 打開當前的“ archive.ear”作為ZipInputStream。
  2. 打開一個新的“ archive.ear.new”作為ZipOutputStream。
  3. 將所有ZipEntries從1.轉移到2。
    1. 當您進入條目“ archive.war”時
    2. 為此打開一個新的ZipInputStream
    3. 為2的條目打開一個新的ZipOutputStream。
    4. 傳輸除“ myFile.properties”以外的所有ZipEntries
    5. 傳輸條目“ myFile.properties”的內容
    6. 刷新您的ZipOutputStream,關閉條目
  4. 將新文件重命名為舊文件

暫無
暫無

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

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