Java io丑陋的try-finally block

标签 java file-io try-catch

是否有一种不那么丑陋的方式来处理 close() 异常以关闭两个流然后:

    InputStream in = new FileInputStream(inputFileName);
    OutputStream out = new FileOutputStream(outputFileName);

    try {
        copy(in, out);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            try {
                // event if in.close fails, need to close the out
                out.close();
            } catch (Exception e2) {}
                throw e; // and throw the 'in' exception
            }
        }
        out.close();
    }

更新:以上所有代码都在一个 try-catch 中,感谢您的警告。

终于(在答案之后):

可以使用Execute Around idiom 来完成一个好的实用方法。 (感谢汤姆·霍廷)。

最佳答案

这是正确的惯用语(而且效果很好):

   InputStream in = null;
   OutputStream out = null;
   try {
       in = new FileInputStream(inputFileName);
       out = new FileOutputStream(outputFileName);
       copy(in, out);
   finally {
       close(in);
       close(out);
   }

  public static void close(Closeable c) {
     if (c == null) return; 
     try {
         c.close();
     } catch (IOException e) {
         //log the exception
     }
  }

这个工作正常的原因是,在你到达 finally 之前抛出的异常将在你的 finally 代码完成后抛出,前提是你的 finally 代码本身不会抛出异常或以其他方式异常终止。

编辑:从 Java 7(和 Android SDK 19 - KitKat)开始,现在有一个 Try with resources 语法来使这个更干净。 this question 中解决了如何处理该问题.

关于Java io丑陋的try-finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2699209/

相关文章:

java - 无法将 5k/秒的记录插入到 impala 中?

java - 如何从Netbeans项目中的jar中排除源包

java - 如何加载大的小程序

c# - 带有catch的catch语句中的单元测试代码

java - 如何定义HADOOP类路径?

c++ - 如何在 C++ 中解析基于文本的表格

c++ - 使用输入名称打开文件

c# - 系统.IO.IOException : file used by another process

Java try catch 错误

Javascript try...catch...else...finally 像 Python、Java、Ruby 等