我正在尝试使用 java DeflaterOutputStream
和 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;
}
}
这是我用来压缩和解压缩字节数组的两种方法。我在网上看到的大多数实现都在解压缩部分使用固定大小的缓冲区数组,但我宁愿尽可能避免这种情况,因为如果我想要任何缓冲区数组,我需要使该缓冲区数组的大小为 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
关于Java字节数组压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332314/