The problem is that TarArchiveOutputStream is not automatically read in the existing archive, what you need to do. Sort of:
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);
A few notes:
- This code does not include exception handling (add appropriate
try-catch-finally blocks) - This code does not process files larger than 2147483647 (
Integer.MAX_VALUE ), since it only reads file sizes in bytes with integer dots (see conversion to int). However, this is not a problem, since Apache Compress does not process files larger than 2 GB in any case.
source share