【问题标题】:How to decompress using Inflater in Java?如何在 Java 中使用 Inflater 解压?
【发布时间】:2014-03-03 03:48:19
【问题描述】:

我对 Java 很陌生。

我有一些代码要压缩,如下所示:

public void compress(OutputStream out) throws IOException
{
    Deflater deflater = new Deflater(1);
    DeflaterOutputStream zOut = new DeflaterOutputStream(out, deflater, 1024);
    DataOutputStream stream = new DataOutputStream(zOut);

    stream.writeShort(200);
    stream.write("test".getBytes("utf-8"));

    zOut.close();
    deflater.end();
}

我正在使用如下功能:

    compress c = new compress();
    FileOutputStream fis = new FileOutputStream("D:\\Temp\\file.bin");
    OutputStream out = fis;
    c.compress(out);
    fis.close(); 

现在,我需要解压我的 file.bin 文件。

我查看了几个示例,但没有一个显示压缩级别。

Deflater 的构造函数有 1 个参数,即压缩级别。

解压的时候不用提吗?

无论如何,请告诉我解压的正确方法。

提前致谢。

【问题讨论】:

  • 就个人而言,我认为您在 API 中运行的有点过低,也许您应该考虑改用 ZipInput/OutputStream

标签: java compression inflate deflate


【解决方案1】:

这应该让您了解如何使用 InflaterInputStream:

public static void decompress(File compressed, File raw)
        throws IOException
    {
        InputStream in =
            new InflaterInputStream(new FileInputStream(compressed));
        OutputStream out = new FileOutputStream(raw);
        byte[] buffer = new byte[1000];
        int len;
        while((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }

希望这会有所帮助。

【讨论】:

  • 你的意思是我解压的时候不用担心压缩级别?
  • 不,你不用担心。
  • 感谢您的回答。
  • 欢迎您@JoshuaSon。玩得开心编码:)
猜你喜欢
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2016-08-24
  • 2011-07-25
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多