我有以下两个代码块,这些代码块用于压缩String。
代码1
public static String compressResponse(String response) throws IOException {
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
try {
deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
} finally {
deflaterOutputStream.close();
}
}
代码2
public static String compressResponse(String response) throws IOException {
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
try {
deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
} finally {
deflaterOutputStream.close();
}
return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
}
只有第二种方法可以正常工作,而第一种方法始终返回空字符串。我知道,由于return块相对于finally块的位置不同,因此会发生这种不同的行为。确切的行为是什么?
最佳答案
原因是因为在第一种方法中,在执行deflaterOutputStream.close();
之前先执行return语句,而在第二种方法中首先执行关闭操作deflaterOutputStream
在关闭连接时将数据写入byteArrayOutputStream
。在deflaterOutputStream
关闭之前,byteArrayOutputStream
不包含数据。