【发布时间】:2015-07-21 00:27:15
【问题描述】:
我是 java 新手,有一个关于 BufferedWriter 和 OutputStream 关闭的问题。
我有一些逻辑,使用 try-with-resources 很不方便:
public static void writeFile(String fileName, String encoding, String payload) {
BufferedWriter writer = null;
OutputStream stream = null;
try {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
stream = needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
所以,我必须自己关闭所有资源。我应该关闭 OutputStream 和 BufferedWriter 吗?还是只关闭BufferedWriter就可以了?
我的代码一切正常吗?
【问题讨论】:
-
为什么你认为在这里使用 try-with-resources 很不方便?这似乎是一个完美的候选人。
-
@vs777 我说不方便,因为有 GZIPOutputStream/FileOutputStream 选择逻辑(基于有效负载大小),我希望将其保留在此方法中。所以我不知道在这种情况下如何实现 try-with-resources 。请举个例子好吗?
标签: java outputstream bufferedwriter