java - 使用 java Deflater/Inflater 和字典有什么问题

标签 java zlib

我尝试将 InflaterDeflater 与字典一起使用,但它不起作用。当我运行这个简单的测试程序时:

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class DictTest {

    public static void main(String[] args) throws Exception {

        final int level = 9;
        final boolean nowrap = true;

        // compress
        final Deflater def = new Deflater(level, nowrap);
        final byte[] abcd = new byte[] { 0x41, 0x42, 0x43, 0x44 };
        def.setDictionary(abcd);
        def.setInput(abcd);
        def.finish();
        final byte[] buf = new byte[1024];
        final int nbytes = def.deflate(buf);
        assert def.finished();
        def.end();

        // decompress
        final Inflater inf = new Inflater(nowrap);
        inf.setInput(buf, 0, nbytes + 1);       // include extra "dummy" byte
        while (true) {
            while (inf.inflate(buf) != 0) {
                // discard
            }
            assert !inf.needsInput();
            if (inf.finished())
                break;
            assert inf.needsDictionary();
            inf.setDictionary(abcd);
            continue;
        }
        inf.end();
    }
}

我得到这个异常:

$ javac DictTest.java && java -ea DictTest
Exception in thread "main" java.util.zip.DataFormatException: invalid distance too far back
    at java.util.zip.Inflater.inflateBytes(Native Method)
    at java.util.zip.Inflater.inflate(Inflater.java:259)
    at java.util.zip.Inflater.inflate(Inflater.java:280)
    at DictTest.main(DictTest.java:27)

我做错了什么?谢谢。

最佳答案

在设置输入之前设置充气器字典。此外,您的无限循环将(永远)运行。你想要类似的东西

final int level = 9;
final boolean nowrap = true;

// compress
final Deflater def = new Deflater(level, nowrap);
final byte[] abcd = new byte[] { 0x41, 0x42, 0x43, 0x44 };
def.setDictionary(abcd);
def.setInput(abcd);
def.finish();
final byte[] buf = new byte[1024];
final int nbytes = def.deflate(buf);
assert def.finished();
def.end();

// decompress
final Inflater inf = new Inflater(nowrap);
inf.setDictionary(abcd);
inf.setInput(buf); // include extra "dummy" byte
while (inf.inflate(buf) != 0) {
    // discard
}
assert !inf.needsInput();
assert inf.needsDictionary();
inf.end();

然后它就可以正常运行。

关于java - 使用 java Deflater/Inflater 和字典有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312897/

相关文章:

zlib - 找不到 ZLIB(缺少 : ZLIB_LIBRARY) (found version "1.2.11")

c - 如何从 ZLIB 压缩器获取 <距离,长度> 对

java - 如何使用 Java 8 lambda 计算序列中多个数字的平均值

java - 构造 LocalDate 时自动移动月/日

java - 安卓Java : Activity doesn't start when the used SharedPreferences

ruby - 不是 gzip 格式 (Zlib::GzipFile::Error) - 在 Ruby 中解压缩 gzip 文件时

javascript - 从因字符串长度而必须压缩的字符串创建可下载链接

java - 从 cmd 运行带有完整路径的 java 类?

java - java中的阿拉伯字符发送电子邮件问题

c++ - 如何返回从inflate()返回解压后的数据实际消耗了多少字节?