2013-05-02 130 views
2

所以我在這裏跟隨了代碼塊:http://commons.apache.org/proper/commons-compress/examples.html,其中據說只需製作一個ZipArchiveEntry然後插入數據即可。正如你可以看到我的代碼如下。將文件添加到現有的Zip歸檔文件中

public void insertFile(File apkFile, File insert, String method) 
    throws AndrolibException { 
     ZipArchiveOutputStream out = null; 
     ZipArchiveEntry entry; 

     try { 
      byte[] data = Files.toByteArray(insert); 
      out = new ZipArchiveOutputStream(new FileOutputStream(apkFile, true)); 
      out.setMethod(Integer.parseInt(method)); 
      CRC32 crc = new CRC32(); 
      crc.update(data); 
      entry = new ZipArchiveEntry(insert.getName()); 
      entry.setSize(data.length); 
      entry.setTime(insert.lastModified()); 
      entry.setCrc(crc.getValue()); 
      out.putArchiveEntry(entry); 
      out.write(data); 
      out.closeArchiveEntry(); 
      out.close(); 
     } catch (FileNotFoundException ex) { 
      throw new AndrolibException(ex); 
     } catch (IOException ex) { 
      throw new AndrolibException(ex); 
     } 
} 

基本上,其傳遞的文件(apkFile),將採取「插入」文件,與其它參數支配該文件的壓縮方法。運行這段代碼會導致0錯誤,但ZIP文件中只包含該「新」文件。它刪除所有以前的文件,然後插入新的文件。

在commons-compresss之前,我不得不將整個Zip複製到一個臨時文件,執行我的更改,然後將該最終Zip文件複製回來。但我認爲這個圖書館能夠解決這個問題?

+0

你是否關閉了'out'? – jtahlborn 2013-05-02 14:52:45

+0

ahh,忘記了一件簡單的事情:/添加關閉現在只是覆蓋整個Zip存檔到我插入的任何文件。 – 2013-05-02 14:56:25

+0

然後,您應該編輯問題並添加該問題。另外,爲什麼使用'String'參數,如果你只是把它轉換爲'int'?爲什麼不使用'int'參數? – acdcjunior 2013-05-02 15:00:55

回答

0

總是想要close()當你完成它們的流(即out.close()),最好在finally塊中。

+1

或者用Java SE 7:最好在try-with-resources塊中。 – Puce 2013-05-02 14:58:53

相關問題