【问题标题】:java file handling and exceptionsjava文件处理和异常
【发布时间】:2011-02-25 21:29:15
【问题描述】:

在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 块......这很丑陋。有没有更好的方法来处理这个问题?

【问题讨论】:

  • 添加另一个 try/catch 块有助于在发生异常时隔离问题
  • @Alpine 它对你的帮助比堆栈跟踪 *shrug* 提供的信息更多
  • @Nathan Hughes:我的表述不好,我意识到了危险,但感谢您指出这一点。

标签: java file-io exception-handling


【解决方案1】:

使用 apache commons io

http://commons.apache.org/proper/commons-io/

看看他们的 FileUtils 类。满满的金子。我说的是黄金......

【讨论】:

  • Apache commons 最好,不用写嵌套try catch
  • 该链接已过期!
【解决方案2】:

这根本不是标准方式。这是不好的方式。

我大部分时间使用的方式是这个:

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
}

【讨论】:

  • 我知道不在 finally 块中关闭它是有风险的,因此我的问题。但是以标准方式命名它确实是一个糟糕的表述。但是 JDK7 信息对我来说是新的,并且看起来很有趣。这是否与 C# 使用的 using{} 语法相媲美,以防您或某人同时了解这两种语言?
  • 我不了解 C#,但它就像 Python 的 with 语法。 python.org/dev/peps/pep-0343
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:
    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!
        }
    }
    

    【讨论】:

    • 有效,但这正是我想避免的。
    • @Rene 你到底想避免什么,你为什么要避免它?
    • 正如我在问题中所写,我只是认为这种方式很丑陋,创建了一大块代码,仅用于处理 3 条语句的异常。所以我的问题纯粹是关于编码风格,也许我太挑剔了;)谢谢你的回复:)
    【解决方案5】:

    最后添加:

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

    【讨论】:

    • 你需要再添加一个 try...catch 这里,这正是我想要避免的
    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多