3

我需要将配置文件添加到现有的 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 的初始内容丢失。“模式”是否设置不正确?

4

2 回答 2

3

问题是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 的文件。
于 2012-04-04T09:16:06.470 回答
1

尝试改变

OutputStream tarOut = new FileOutputStream(f2);

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

于 2012-04-04T08:09:20.170 回答