Tar problem with apache commons compress

10,364

Solution 1

You're not closing the TarArchiveOutputStream. Add aos.close() after aos.finish()

Solution 2

Small correction to the code above. It does not close input stream, while Apache lib assumes that stream is managed by calling client. See the fix below (put this code after the line 'aos.putArchiveEntry(entry)') :

FileInputStream fis = new FileInputStream(fileForPuttingIntoTar);
IOUtils.copy(fis, aos);
fis.close();
aos.closeArchiveEntry();
Share:
10,364
Pierre Gayvallet
Author by

Pierre Gayvallet

I'm a freelance full stack developer specialized in web application, with 8 years of experiences, and more than 5 developing rich apps, starting with mootools, jQuery, then backbone, and now angularJS and react depending on the needs.

Updated on June 04, 2022

Comments

  • Pierre Gayvallet
    Pierre Gayvallet almost 2 years

    I'm having a hard time trying to tar some files using the compress library.

    My code is the following, and is taken from the commons.compress wiki exemples :

        private static File createTarFile(String[] filePaths, String saveAs) throws Exception{
    
        File tarFile = new File(saveAs);
        OutputStream out = new FileOutputStream(tarFile);
    
        TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
    
        for(String filePath : filePaths){
            File file = new File(filePath);
            TarArchiveEntry entry = new TarArchiveEntry(file);
            entry.setSize(file.length());
            aos.putArchiveEntry(entry);
            IOUtils.copy(new FileInputStream(file), aos);
            aos.closeArchiveEntry();
        }
        aos.finish();
        out.close();
    
    
        return tarFile;
    }
    

    There is no error during the process, but when I try to untar the file, I got the following :

    XXXX:XXXX /home/XXXX$ tar -xf typeCommandes.tar
    tar: Unexpected EOF in archive
    tar: Unexpected EOF in archive
    tar: Error is not recoverable: exiting now
    

    Also, the archive IS slighty smaller in size than the original file, which isnt normal for a tar, so there DO is a problem...

    -rw-r--r--  1 XXXX nobody 12902400 Jan 14 17:11 typeCommandes.tar
    -rw-r--r--  1 XXXX nobody 12901888 Jan 14 17:16 typeCommandes.csv
    

    Anyone can tell me what I'm doing wrong ? Thanks