在java中处理文件读写的标准方法是这样的:
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
oos.writeObject(h);
oos.close();
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
但我对这段代码感到困扰,因为如果抛出异常,这里可能永远不会关闭文件。当然,我们可以添加一个finally子句并初始化try块外的ObjectOutputStream。但是,当你这样做时,你需要再次在finally块中添加另一个try / catch块...这只是丑陋的。有没有更好的方法来处理这个问题?
答案 0 :(得分:8)
答案 1 :(得分:6)
这根本不是标准方式。这是不好的方式。
我大部分时间使用的方式都是这个:
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
}
}
}
finally块中的代码可以放在辅助方法中,或者你可以使用commons IO来安静地关闭流,如其他答案中所述。
必须始终在finally块中关闭流。
请注意,JDK7将使用新语法更容易,新语法会在try块结束时自动关闭流:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) {
// use out
}
答案 2 :(得分:3)
这就是为什么我使用commons-io的IOUtils.closeQuitely(...)
try
{
...
}
finally
{
IOUtils.closeQuietly(costream);
}
答案 3 :(得分:0)
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
oos.writeObject(h);
//oos.close(); // glow coder removed
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
// glowcoder adds:
finally {
try {
oos.close();
}
catch(IOException ex) {
// dammit we tried!
}
}
答案 4 :(得分:0)
最后添加:
finally{
if(oos != null)
oos.close();
}