Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all the entries of a tar file in java?

Tags:

java

file

list

tar

I want to list all the entries of a tar file in my Java program. How is it possible ? For zip files, I can use the below code:

ZipFile zf = new ZipFile("ReadZip.zip");
Enumeration entries = zf.entries();
while (entries.hasMoreElements()) {.....}

But I am not sure for the tar files. Can anybody help? I am using org.apache.tools.tar.*

like image 799
JavaUser Avatar asked Jan 12 '12 06:01

JavaUser


2 Answers

Apache Commons Compress (http://commons.apache.org/compress/) is easy to use.

Here's an example of reading a tar's entries:

import java.io.FileInputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;

public class Taread {
    public static void main(String[] args) {
        try {
            TarArchiveInputStream tarInput = new TarArchiveInputStream(new FileInputStream(args[0]));
            TarArchiveEntry entry;
            while (null!=(entry=tarInput.getNextTarEntry())) {
                System.out.println(entry.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 172
craigmj Avatar answered Sep 29 '22 02:09

craigmj


This API is very similar to using Java's own ZipInputStream.

To start off:

TarInputStream tis = new TarInputStream(new FileInputStream("myfile.tar"));
try
{
    TarEntry entry;
    do
    {
        entry = tis.getNextEntry();

        //Do something with the entry
    }
    while (entry != null);
}
finally
{
    tis.close();
}

More examples with different APIs are [here][2].
like image 28
prunge Avatar answered Sep 29 '22 03:09

prunge