Ren*_*ene 4 java file-io exception-handling
在java中处理文件读写的标准方法是这样的:
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
oos.writeObject(h);
oos.close();
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
Run Code Online (Sandbox Code Playgroud)
但是我对这段代码感到困扰,因为如果抛出异常,这里可能永远不会关闭文件.当然,我们可以添加一个finally子句并初始化try块外的ObjectOutputStream.但是,当你这样做时,你需要再次在finally块中添加另一个try/catch块...这只是丑陋的.有没有更好的方法来处理这个问题?
这根本不是标准方式.这是不好的方式.
我大多数时间使用的方式是这个:
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("file.dat"));
// use out
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// nothing to do here except log the exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
finally块中的代码可以放在辅助方法中,或者您可以使用commons IO安静地关闭流,如其他答案中所述.
必须始终在finally块中关闭流.
请注意,JDK7将使用新语法更容易,新语法将自动关闭try块末尾的流:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) {
// use out
}
Run Code Online (Sandbox Code Playgroud)