【问题标题】:How to list all the entries of a tar file in java?如何在java中列出tar文件的所有条目?
【发布时间】:2012-02-08 11:44:27
【问题描述】:

我想在我的 Java 程序中列出一个 tar 文件的所有条目。这怎么可能 ? 对于 zip 文件,我可以使用以下代码:

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

但我不确定 tar 文件。有人可以帮忙吗?我正在使用org.apache.tools.tar.*

【问题讨论】:

    标签: java list file tar


    【解决方案1】:

    Apache Commons Compress (http://commons.apache.org/compress/) 易于使用。

    以下是读取 tar 条目的示例:

    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();
            }
        }
    }
    

    【讨论】:

    • 我可以使用 TarArchieveInputStream 和 ZipInputStream 使用单独的函数列出 Zip 和 tar.gz 的所有条目,但是有没有办法在单个函数中处理这两者? 'case zip() => new ZipInputStream(src.open) case tar() => new TarArchiveInputStream(new GzipCompressorInputStream(file.open))
    【解决方案2】:

    这个API与使用Java自己的ZipInputStream非常相似。

    开始:

    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].
    

    【讨论】:

    • 很遗憾您忘记添加链接(
    【解决方案3】:

    要读取 Java .jar 文件,您可以使用“jar”工具...或解压缩。 .Jar 文件为 .Zip 格式。

    但是,要读取 *nix .tar 文件,您需要使用“tar”工具。

    如果您使用的是 Windows,我建议您尝试 7-Zip。这是一个方便的工具,可以识别无数种格式……包括 .zip(因此也是 .jar)和 tar:

    http://www.7-zip.org/

    如果您必须以编程方式进行,我想 Apache Ant API“tar”是一个不错的选择。它为您提供了“TarEntry”列表:

    http://www.jajakarta.org/ant/ant-1.6.1/docs/ja/manual/api/org/apache/tools/tar/TarEntry.html

    【讨论】:

      【解决方案4】:

      您使用 ZIP 文件代码列出目录....

      你可以查看 linux 的 tar 文件

      http://www.java2s.com/Code/Java/File-Input-Output/TapeArchiveListerTarfile.htm

      供进一步参考....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-13
        • 2011-03-01
        • 2010-09-23
        相关资源
        最近更新 更多