我需要將配置文件添加到現有tar文件。我正在使用apache.commons.compress庫。以下代碼片段正確添加條目,但會覆蓋tar文件的現有條目。向tar文件添加條目而不覆蓋其現有內容
public static void injectFileToTar() throws IOException, ArchiveException {
String agentSourceFilePath = "C:\\Work\\tar.gz\\";
String fileToBeAdded = "activeSensor.cfg";
String unzippedFileName = "sample.tar";
File f2 = new File(agentSourceFilePath+unzippedFileName); // Refers to the .tar file
File f3 = new File(agentSourceFilePath+fileToBeAdded); // The new entry to be added to the .tar file
// Injecting an entry in the tar
OutputStream tarOut = new FileOutputStream(f2);
TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("tar", tarOut);
TarArchiveEntry entry = new TarArchiveEntry(fileToBeAdded);
entry.setMode(0100000);
entry.setSize(f3.length());
aos.putArchiveEntry(entry);
FileInputStream fis = new FileInputStream(f3);
IOUtils.copy(fis, aos);
fis.close();
aos.closeArchiveEntry();
aos.finish();
aos.close();
tarOut.close();
}
在檢查焦油,只有「activeSensor.cfg」的文件被發現,焦油的初始內容不翼而飛。 「模式」設置不正確?
@biggusjimmusThanks – 2012-04-04 08:32:21
謝謝。我做了上述改變。 tar內容被保留,但新條目(activeSensor.cfg)不會被添加到焦油中。我是否將傳遞給TarArchiveEntry構造函數的路徑或參數搞亂了? – 2012-04-04 08:44:51
在我去這裏搜索之前,我正在使用這種方法。似乎導致條目超出tar歸檔的末尾,所以我會得到一個錯誤,但我的新文件不會在那裏。 – froggythefrog 2017-05-11 02:09:30