【问题标题】:Reading gzip files inside gzip file using Java使用Java读取gzip文件中的gzip文件
【发布时间】:2015-08-19 16:26:31
【问题描述】:

使用 Java 我必须读取位于另一个 .tar.gz 中的 gz 文件中的文本文件

gz_ltm_logs.tar.gz 是文件名。然后它里面有文件 ltm.1.gz、ltm.2.gz,然后这些文件里面有文本文件。

我只想使用 java.util.zip.* 来实现,但如果不可能,那么我可以查看其他库。 我想我可以使用 java.util.zip 来做到这一点。但似乎并不简单

【问题讨论】:

  • Gzip 无法将多个文件单独压缩为一个。我们在谈论 tar.gz 吗?
  • 是的 gz_ltm_logs.tar.gz 是文件名。我认为它只是等于.gz。然后它里面有文件 ltm.1.gz, ltm.2.gz

标签: java gzip


【解决方案1】:

这里有一些代码可以给你一个想法。此方法将尝试将给定的 tar.gz 文件提取到 outputFolder。

public static void extract(File input, File outputFolder) throws IOException {
    byte[] buffer = new byte[1024];

    GZIPInputStream gzipFile = new GZIPInputStream(new FileInputStream(input));
    ByteOutputStream tarStream = new ByteOutputStream();

    int gzipLengthRead;
    while ((gzipLengthRead = gzipFile.read(buffer)) > 0){
        tarStream.write(buffer, 0, gzipLengthRead);
    }

    gzipFile.close();

    org.apache.tools.tar.TarInputStream tarFile = null;

    // files inside the tar
    OutputStream out = null;
    try {
        tarFile = new org.apache.tools.tar.TarInputStream(tarStream.newInputStream());
        tarStream.close();

        TarEntry entry = null;

        while ((entry = tarFile.getNextEntry()) != null) {

            String outFilename = entry.getName();

            if (entry.isDirectory()) {
                File directory = new File(outputFolder, outFilename);
                directory.mkdirs();
            } else {
                File outputFile = new File(outputFolder, outFilename);
                File outputDirectory = outputFile.getParentFile();
                if (!outputDirectory.exists()) {
                    outputDirectory.mkdirs();
                }
                out = new FileOutputStream(outputFile);

                // Transfer bytes from the tarFile to the output file
                int innerLen;

                while ((innerLen = tarFile.read(buffer)) > 0) {
                    out.write(buffer, 0, innerLen);
                }
                out.close();
            }
        }
    } finally {
        if (tarFile != null) {
            tarFile.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多