我希望有人可以阐明我在下面的代码中遇到的问题。
private static String encode(String data) throws IOException {
try (
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(data.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(out));
) {
char[] charBuffer = new char[data.length()];
while (br.read(charBuffer) != -1) {
writer.write(charBuffer);
}
// writer.close();
return new String(Base64.encodeBase64(out.toByteArray()));
}
}
我的测试值是
This is some text that I can test some base64 encoding with.
I am getting a strange problem with the encoded value
当 writer.close 被注释掉时,我的输出是
H4sIAAAAAAAAAA==
当它没有被评论时,我的输出是
H4sIAAAAAAAAACWMzQ2DMBSD70jdwRP0VLED9y7wACuJRJKKZ37GJxTJF/uz/Y3J0eQ1E+IpKJowYLLSvOshozn7D1imOqcScCTF96sbYBmB0p0ZXKuVQPzWOi7M/1b747PjjN2WjRd08DfZcwAAAA==
第二个输出是正确的值,可以解码回原始值。据我了解,流程如下:
- 尝试代码被执行
- 返回值被评估和存储
- 资源全部关闭
- 返回值被返回。
那么为什么需要关闭编写器才能使输出正确呢?