以下代码基于java.util.zip.Deflater的javadocs示例。我唯一做的更改是创建了一个名为dict的字节数组,并使用setDictionary(byte [])方法在Deflater和Inflater实例上设置字典。
问题在于,当我用与Deflater相同的确切数组调用Inflater.setDictionary()时,会出现IllegalArgumentException异常。
以下是相关代码:
问题在于,当我用与Deflater相同的确切数组调用Inflater.setDictionary()时,会出现IllegalArgumentException异常。
以下是相关代码:
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class DeflateWithDictionary {
public static void main(String[] args) throws Exception {
String inputString = "blahblahblahblahblah??";
byte[] input = inputString.getBytes("UTF-8");
byte[] dict = "blah".getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.setDictionary(dict);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
decompresser.setDictionary(dict); //IllegalArgumentExeption thrown here
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result);
decompresser.end();
// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");
System.out.println("Decompressed String: " + outputString);
}
}
如果我在没有设置字典的情况下尝试解压相同的压缩字节,不会出现错误,但返回的结果为零字节。
使用Deflater / Inflater时,是否需要特别注意使用自定义字典?
needsDictionary()
之所以存在是因为zlib格式允许在同一应用程序中使用不同的字典,并在文件头中指定字典的Adler32校验和。为了读取此标头(并允许解压缩方面的应用程序选择正确的字典),需要首先调用inflate
。 - Paŭlo Ebermann