【问题标题】:How to print the content of a tar.gz file with Java?如何使用 Java 打印 tar.gz 文件的内容?
【发布时间】:2011-02-23 16:53:34
【问题描述】:

我必须实现一个允许打印 tar.gz 文件中所有文件内容的应用程序。

例如:
如果我在名为 testx 的文件夹中有三个这样的文件:
A.txt 包含“God Save The Queen”字样
B.txt 包含“Ubi maior,minor cessat”字样
C.txt.gz 是一个使用 gzip 压缩的文件,其中包含 c.txt 文件,其中包含“Hello America!!”字样

于是我压缩了testx,得到压缩后的tar文件:testx.tar.gz。

因此,我想使用我的 Java 应用程序在控制台中打印:
《天佑女王》
“Ubi maior,次要停止”
“你好美国!!”

我已经实现了 ZIP 版本,它运行良好,但是保留来自 apache ant http://commons.apache.org/compress/ 的 tar 库,我注意到它不像 ZIP java utils 那样容易。

有人可以帮我吗?

我已经开始在网上寻找以了解如何实现我的目标,所以我有以下代码:

GZIPInputStream gzipInputStream=null;
gzipInputStream = new GZIPInputStream( new FileInputStream(fileName));
TarInputStream is =  new TarInputStream(gzipInputStream);
TarEntry entryx = null;

while((entryx = is.getNextEntry()) != null) {
    if (entryx.isDirectory()) continue;
    else {
        System.out.println(entryx.getName());
        if ( entryx.getName().endsWith("txt.gz")){
            is.copyEntryContents(out);
            // out is a OutputStream!! 
        }
    }
}

所以在is.copyEntryContents(out) 行中,可以将通过OutputStream 的流保存在文件中,但我不想要它!在保留第一个条目 ZipEntry 后的 zip 版本中,我们可以从压缩的根文件夹 testx.tar.gz 中提取流,然后创建一个新的 ZipInputStream 并播放它来获取内容。

是否可以使用 tar.gz 文件执行此操作?

谢谢。

【问题讨论】:

标签: java compression tar


【解决方案1】:

上网,我在http://hype-free.blogspot.com/2009/10/using-tarinputstream-from-java.html遇到了一个有趣的想法。

将我们的 TarEntry 转换为 Stream 后,我们可以采用与 Zip 文件相同的想法,例如:

InputStream tmpIn = new StreamingTarEntry(is,  entryx.getSize());
// use BufferedReader to get one line at a time
BufferedReader gzipReader = new BufferedReader(
                       new InputStreamReader(
                        new GZIPInputStream(
                        inputZip )));

while (gzipReader.ready()) { System.out.println(gzipReader.readLine()); }
gzipReader.close();

因此,您可以使用此代码打印文件 testx.tar.gz 的内容 ^_^

【讨论】:

    【解决方案2】:

    为了不必写信给File,您应该使用ByteArrayOutputStream,并使用正确编码的public String toString(String charsetName)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多