将条目添加到tar文件而不覆盖其现有内容

时间:2012-04-04 07:34:41

标签: java

我需要将配置文件添加到现有的tar文件中。我正在使用 apache.commons.compress 库。以下代码段正确添加了该条目,但会覆盖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(); 

}

在检查tar时,只找到“activeSensor.cfg”文件,并且发现tar的初始内容丢失。 “模式”设置不正确吗?

2 个答案:

答案 0 :(得分:2)

问题是TarArchiveOutputStream不会自动读取现有存档,这是您需要执行的操作。有点像:

CompressorStreamFactory csf = new CompressorStreamFactory();
ArchiveStreamFactory asf = new ArchiveStreamFactory();

String tarFilename = "test.tgz";
String toAddFilename = "activeSensor.cfg";
File toAddFile = new File(toAddFilename);
File tempFile = File.createTempFile("updateTar", "tgz");
File tarFile = new File(tarFilename);

FileInputStream fis = new FileInputStream(tarFile);
CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP, fis);
ArchiveInputStream ais = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

FileOutputStream fos = new FileOutputStream(tempFile);
CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, fos);
ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos);

// copy the existing entries    
ArchiveEntry nextEntry;
while ((nextEntry = ais.getNextEntry()) != null) {
    aos.putArchiveEntry(nextEntry);
    IOUtils.copy(ais, aos, (int)nextEntry.getSize());
    aos.closeArchiveEntry();
}

// create the new entry
TarArchiveEntry entry = new TarArchiveEntry(toAddFilename);
entry.setSize(toAddFile.length());
aos.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(toAddFile), aos, (int)toAddFile.length());
aos.closeArchiveEntry();

aos.finish();

ais.close();
aos.close();

// copies the new file over the old
tarFile.delete();
tempFile.renameTo(tarFile);

几点说明:

  • 此代码不包含任何异常处理(请添加相应的try-catch-finally块)
  • 此代码不处理大小超过2147483647(Integer.MAX_VALUE)的文件,因为它只将文件大小读取为整数精度字节(请参阅转换为int)。但是,这不是问题,因为Apache Compress无论如何都不能处理超过2 GB的文件。

答案 1 :(得分:0)

尝试更改

OutputStream tarOut = new FileOutputStream(f2);

OutputStream tarOut = new FileOutputStream(f2, true); //设置追加到真