【发布时间】:2011-08-27 07:42:49
【问题描述】:
这是一个我有疑问的例子(它来自另一个 SO 问题):
public static void writeToFile (final String filename)
{
PrintWriter out = null;
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filename);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos, "UTF-8")));
for (final String line : log)
{
out.println(line);
}
out.flush();
out.close();
}
catch (final Exception e)
{
System.err.println("Unable to write log to file.");
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (final IOException e)
{
System.err.println("Unable to write log to file.");
}
}
}
}
现在我认为这段代码可以正常工作,并在应该的地方释放所有资源等。我的问题是:
我为什么要关闭
try-catch-finally的finally部分中的FileOutputStream?当然我可以将代码按顺序放在try-catch之后?为什么我必须单独关闭
FileOutputStream而不是简单地将new OutputStreamWriter(fos, ...替换为new OutputStreamWriter(new FileOutputStream(filename), ...?如果我先关闭 FileOutputStream,那会自动关闭其余部分并释放资源吗?同样的问题也适用于套接字,如果我关闭套接字连接,是否会自动关闭流读取器/写入器并释放资源?我被反复告知要确保我使用“UTF-8”读写流,因为不同的系统具有不同的字符集(或类似的字符集)。这在读取/写入 RAW 字节数据(例如来自非文本文件或加密结果)时是否仍然适用,因为我认为字符集只能处理文本字符?
【问题讨论】:
-
移动代码'out.close();' for out = new PrintWriter(...) 最终阻塞,与 'fos = new FileOutputStream(filename);' 的定义相同
-
您写道:“我现在找不到线程”。也许您的意思是 22answers.com 上的 "When to use which Writer subclass in Java; common practices" 线程。
-
@mKorbel - 谢谢。 @Marnix Klooster - 是的,它实际上是SO帖子的副本。 @Jonathon - 感谢您的编辑。
标签: java sockets character-encoding io try-catch