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.*
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();
}
}
}
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With