实际上,我在提出问题时就想出了这一点,但我认为无论如何我应该提出问题,以便其他人可以从我的奋斗中受益。
事实证明,您必须在设置输入之后但 在 设置字典 之前
调用inflate()一次。返回的值将为0,然后对needsDictionary()的调用将返回true。之后,您可以设置字典并再次调用充气。
修改后的代码如下:
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); byte[] result = new byte[100]; decompresser.inflate(result); decompresser.setDictionary(dict); int resultLength = decompresser.inflate(result); decompresser.end(); // Depre the bytes into a String String outputString = new String(result, 0, resultLength, "UTF-8"); System.out.println("Decompressed String: " + outputString); }}从API设计的角度来看,这似乎非常直觉且笨拙,因此,如果有更好的选择,请告诉我。



