views:

669

answers:

4

Hello,

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

+1  A: 

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

Kevin
Yea that was it... Thanks
Spark
A: 

the example here -> http://commons.apache.org/compress/examples.html uses the method putNextEntry(entry) which you seem to omit.

Yoni
A: 

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();
Alex
A: 

very good post, it helped me a lot.

thank you!!!!!!!!!!!!!!!!!!

maxpade