Lev*_*ock 9 java compression arrays
我正在尝试使用 javaDeflaterOutputStream和InflaterOutputStream类来压缩字节数组,但两者似乎都无法正常工作。我认为我错误地实施了它们。
public static byte[] compress(byte[] in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DeflaterOutputStream defl = new DeflaterOutputStream(out);
defl.write(in);
defl.flush();
defl.close();
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
System.exit(150);
return null;
}
}
public static byte[] decompress(byte[] in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream infl = new InflaterOutputStream(out);
infl.write(in);
infl.flush();
infl.close();
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
System.exit(150);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我用来压缩和解压缩字节数组的两种方法。我在网上看到的大多数实现都使用固定大小的缓冲区数组来进行解压缩部分,但如果可能的话,我希望避免这种情况,因为如果我想要任何缓冲区数组,我需要使该缓冲区数组的大小为 1显着压缩。
如果有人可以向我解释我做错了什么,我将不胜感激。另外,为了解释为什么我知道这些方法无法正常工作:它输出的“压缩”字节数组始终大于未压缩的字节数组,无论我尝试提供什么大小的字节数组。
这将取决于您要压缩的数据。例如,如果我们采用一个0字节数组,它可以很好地压缩:
byte[] plain = new byte[10000];
byte[] compressed = compress(plain);
System.out.println(compressed.length); // 33
byte[] result = decompress(compressed);
System.out.println(result.length); // 10000
Run Code Online (Sandbox Code Playgroud)