2011-02-25 45 views
4

的处理文件的阅读和使用Java语言编写的标准方法是这样的:的java文件处理和异常

try 
{ 
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat")); 
    oos.writeObject(h); 
    oos.close(); 
} 
catch (FileNotFoundException ex) 
{ 
} 
catch (IOException ex) 
{ 
} 

但我通过代码困扰,因为它可能是可能在这里该文件从未关闭,如果抛出异常。当然,我们可以添加一个finally子句并在try块外面初始化ObjectOutputStream。然而,当你这样做时,你需要再次添加另一个try/catch块再次嵌入finally块中......这很丑陋。有没有更好的方法来处理这个问题?

+0

添加另一个try/catch块可以帮助您隔离时的问题发生异常 – Alpine

+1

@Alpine对堆栈跟踪提供的信息没有任何帮助* * ^^^ – corsiKa

+0

@Nathan Hughes:我的部分的表述不好,意识到危险,但感谢您指出了这一点。 – Rene

回答

3

这就是我使用commons-io的IOUtils.closeQuitely(...)

try 
{ 
... 
} 
finally 
{ 
    IOUtils.closeQuietly(costream); 
} 
+0

看起来有趣,谢谢! – Rene

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! 
    } 
} 
+0

工程,但这正是我想要避免做的。 – Rene

+0

@Rene你究竟想要避免什么,为什么你想避免它? – corsiKa

+0

正如我在我的问题中写的,我只是认为这种方式很难看,创建了一个巨大的代码块,用于处理3条语句的异常。所以我的问题纯粹是关于编码风格,也许我对它太挑剔了;)感谢您的回应无论如何:) – Rene

0

添加此最后:

finally{ 
    if(oos != null) 
     oos.close(); 
} 
+0

您需要添加另一个尝试...赶上这里,这正是我想避免 – Rene

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 
} 
+0

上午意识到不在finally块中关闭它是有风险的,因此我的问题。但将其命名为标准方式确实是一个糟糕的表述。然而,JDK7信息对我来说是新的,而且看起来很有趣。这与C#使用的使用{}语法相媲美,以防您或某人知道这两种语言? – Rene

+0

我不知道C#,但它就像Python的'with'语法。 http://www.python.org/dev/peps/pep-0343/ – z0r