【问题标题】:decompress (unzip) file in java that have been compressed by .net system.io.compression.gzipstream用.net system.io.compression.gzipstream 压缩的java文件解压(解压)
【发布时间】:2016-11-16 11:33:20
【问题描述】:

我有一个文件已被 .net 应用程序使用 system.io.compression.gzipstream 库压缩 (zip)。 我尝试在 java 中使用 java.util.zip.GZIPInputStream 解压缩(解压缩)它。 它扔了:

java.io.EOFException 在 java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:246) 在 java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:237) 在 java.util.zip.GZIPInputStream.readUInt(GZIPInputStream.java:229) 在 java.util.zip.GZIPInputStream.readTrailer(GZIPInputStream.java:197) 在 java.util.zip.GZIPInputStream.read(GZIPInputStream.java:92) 在 java.io.FilterInputStream.read(FilterInputStream.java:90) 在 juwdemoproj.FileWriterTest.gunzipIt(FileWriterTest.java:353) 在 juwdemoproj.FileWriterTest.main(FileWriterTest.java:51)

我的示例代码:

    public static void gunzipIt() {
    byte[] buffer = new byte[1024];

    String zipFilePath = "C:\\Juw\\JR\\file\\output\\020030214112016.zip";
    String destDirectory = "C:\\Juw\\JR\\file\\output\\targetUnzip";

    try {
        GZIPInputStream gzis =
            new GZIPInputStream(new FileInputStream(zipFilePath));

        FileOutputStream out = new FileOutputStream(destDirectory);

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

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

        System.out.println("Done");

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

问题: - 当文件被.net应用程序压缩时,是否可以在java中解压缩文件? - 有没有可以达到上述要求的zip库?

谢谢

【问题讨论】:

  • ZIP 和 GZip 是两种不同且不兼容的格式。我建议您将 .zip 作为 ZIP 而不是 .gz 文件打开。
  • @PeterLawrey 好吧,OP 确实说它是使用 .NET 的gzipstream 压缩的,所以可能只是文件扩展名错误。无论哪种方式,OP 似乎确实混淆了 Zip 和 GZip,因为压缩文件应该有 .zip 文件扩展名,而 gzip 文件应该有 .gz 文件扩展名。
  • 嗨@PeterLawrey,是的,我的客户将其保存为 .zip 文件扩展名,但他们使用 gzipstream 库。我可以在他们的代码中看到它。
  • @Andreas,当我尝试在 java 中解压缩时,扩展名命名是否有任何影响?
  • 此错误表明文件被截断。他们是否正确关闭了流。可以被其他工具读取吗?

标签: java .net gzip


【解决方案1】:

我使用此代码,它解决了我的问题。

public void gunzipIt(){

 byte[] buffer = new byte[1024];
 boolean isValid = true;

 try{

     GZIPInputStream gzis =
        new GZIPInputStream(new FileInputStream(INPUT_GZIP_FILE));

     FileOutputStream out =
        new FileOutputStream(OUTPUT_FILE);

    while (isValid) {

        int len;

        try{
            len = gzis.read(buffer);
        }catch(Exception ex){
            len = 0;
            isValid = false;
        }

        if (len > 0) {
            out.write(buffer, 0, len);
        }else{

            isValid = false;
        }
    }

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

    System.out.println("Done");

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

}

在文件末尾有一个空字符串,所以它会抛出错误。我从我的同事那里得到了这个代码,它可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2022-07-27
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2013-03-09
    相关资源
    最近更新 更多