I have following two code block, which I use to compress a String.
code 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();
}
}
code 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);
}
Only the second method works fine where first method always return an empty String. I understand the this different behavior occurs due to different placement of return block with respect to finally block. What is the exact behavior for this?