【问题标题】:Extract .gz files in java在java中提取.gz文件
【发布时间】:2023-07-19 08:26:01
【问题描述】:

我正在尝试在 java 中解压缩一些 .gz 文件。经过一些研究,我写了这个方法:

    public static void gunzipIt(String name){

    byte[] buffer = new byte[1024];

    try{

        GZIPInputStream gzis = new GZIPInputStream(new FileInputStream("/var/www/html/grepobot/API/"+ name + ".txt.gz"));
        FileOutputStream out = new FileOutputStream("/var/www/html/grepobot/API/"+ name + ".txt");

        int len;
        while ((len = gzis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }

        gzis.close();
        out.close();

        System.out.println("Extracted " + name);

    } catch(IOException ex){
        ex.printStackTrace();
    }
}

当我尝试执行它时,我得到了这个错误: java.util.zip.ZipException: 不是 GZIP 格式

我该如何解决?提前感谢您的帮助

【问题讨论】:

  • 使用命令file /var/www/html/grepobot/API/someName.txt.gz验证文件是否为gzip压缩数据?
  • 当然是。如果我执行 gunzip /var/www/html/grepobot/API/someName.txt.gz 它可以工作。目前我用 Process 执行命令

标签: java unzip gzip


【解决方案1】:

测试一个示例、正确的 gzip 压缩文件,看看问题是否出在您的代码中。

有许多可能的方法来构建 (g)zip 文件。您的文件的构建方式可能与 Java 的内置支持所期望的不同,一个解压缩器理解压缩变体这一事实并不能保证 Java 也能识别该变体。请使用file 和/或其他可以告诉您在压缩文件时使用了哪些选项的解压缩实用程序来验证确切的文件类型。您还可以使用hexdump 等工具查看文件本身。这是以下命令的输出:

$ hexdump -C lgpl-2.1.txt.gz | head

00000000  1f 8b 08 08 ed 4f a9 4b  00 03 6c 67 70 6c 2d 32  |.....O.K..lgpl-2|
00000010  2e 31 2e 74 78 74 00 a5  5d 6d 73 1b 37 92 fe 8e  |.1.txt..]ms.7...|
00000020  ba 1f 81 d3 97 48 55 34  13 7b 77 73 97 78 2b 55  |.....HU4.{ws.x+U|
00000030  b4 44 d9 bc 95 25 2d 29  c5 eb ba ba aa 1b 92 20  |.D...%-)....... |
00000040  39 f1 70 86 99 17 29 bc  5f 7f fd 74 37 30 98 21  |9.p...)._..t70.!|
00000050  29 7b ef 52 9b da 58 c2  00 8d 46 bf 3c fd 02 d8  |){.R..X...F.<...|
00000060  da fe 3f ef 6f 1f ed cd  78 36 1b 4f ed fb f1 ed  |..?.o...x6.O....|
00000070  78 3a ba b1 f7 8f ef 6e  26 97 96 fe 1d df ce c6  |x:.....n&.......|
00000080  e6 e0 13 f9 e7 57 57 56  69 91 db 37 c3 d7 03 7b  |.....WWVi..7...{|
00000090  ed e6 65 93 94 7b fb fa  a7 9f 7e 32 c6 5e 16 bb  |..e..{....~2.^..|

在这种情况下,我在this license text 上使用了标准gzip。第一个字节对 GZipped 文件是唯一的(尽管它们没有指定变体) - 如果您的文件不是以 1f 8b 开头,Java 会抱怨,无论剩余内容如何。

如果问题是由文件引起的,那么 Java 中可用的其他解压缩库可能会正确处理该格式 - 例如,请参阅Commons Compress

【讨论】:

    【解决方案2】:
    import com.horsefly.utils.GZIP;
    import org.apache.commons.io.FileUtils;
    ....
    String content = new String(new GZIP().decompresGzipToBytes(FileUtils.readFileToByteArray(fileName)), "UTF-8");
    

    以防有人需要。

    【讨论】: