String
我们可以byte[]
轻松拆卸
String s = "my string";
byte[] b = s.getBytes();
System.out.println(new String(b)); // my string
然而,当涉及压缩时,似乎存在一些问题。假设您有 2 种方法,compress
并且uncompress
(下面的代码可以正常工作)
public static byte[] compress(String data)
throws UnsupportedEncodingException, IOException {
byte[] input = data.getBytes("UTF-8");
Deflater df = new Deflater();
df.setLevel(Deflater.BEST_COMPRESSION);
df.setInput(input);
ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
df.finish();
byte[] buff = new byte[1024];
while (!df.finished()) {
int count = df.deflate(buff);
baos.write(buff, 0, count);
}
baos.close();
byte[] output = baos.toByteArray();
return output;
}
public static String uncompress(byte[] input)
throws UnsupportedEncodingException, IOException,
DataFormatException {
Inflater ifl = new Inflater();
ifl.setInput(input);
ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
byte[] buff = new byte[1024];
while (!ifl.finished()) {
int count = ifl.inflate(buff);
baos.write(buff, 0, count);
}
baos.close();
byte[] output = baos.toByteArray();
return new String(output);
}
我的测试工作如下(工作正常)
String text = "some text";
byte[] bytes = Compressor.compress(text);
assertEquals(Compressor.uncompress(bytes), text); // works
没有别的原因,为什么不呢,我想修改第一个方法以返回 aString
而不是byte[].
所以我return new String(output)
从compress
方法并将我的测试修改为:
String text = "some text";
String compressedText = Compressor.compress(text);
assertEquals(Compressor.uncompress(compressedText.getBytes), text); //fails
这个测试失败了java.util.zip.DataFormatException: incorrect header check
这是为什么?需要做什么才能使其发挥作用?