java尝试finally块来关闭流

问题描述 投票:29回答:8

我想在finally块中关闭我的流,但它抛出一个IOException所以我似乎必须在我的try块中嵌套另一个finally块以关闭流。这是正确的方法吗?看起来有点笨重。

这是代码:

 public void read() {
    try {
        r = new BufferedReader(new InputStreamReader(address.openStream()));
        String inLine;
        while ((inLine = r.readLine()) != null) {
            System.out.println(inLine);
        }
    } catch (IOException readException) {
        readException.printStackTrace();
    } finally {
        try {
            if (r!=null) r.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }


}
java file-io stream try-catch finally
8个回答
24
投票

看起来有点笨重。

它是。至少java7尝试使用资源修复它。

在java7之前你可以制作一个吞下它的closeStream函数:

public void closeStream(Closeable s){
    try{
        if(s!=null)s.close();
    }catch(IOException e){
        //Log or rethrow as unchecked (like RuntimException) ;)
    }
}

或者把try ...终于在try catch中:

try{
    BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
    try{

        String inLine;
        while ((inLine = r.readLine()) != null) {
            System.out.println(inLine);
        }
    }finally{
        r.close();
    }
}catch(IOException e){
    e.printStackTrace();
}

它更加冗长,并且最终会在try中隐藏一个例外,但它在语义上更接近Java 7中引入的try-with-resources


35
投票

此外,如果您使用的是Java 7,则可以使用try-with-resources statement

try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) {
    String inLine;
    while ((inLine = r.readLine()) != null) {
        System.out.println(inLine);
    }
} catch(IOException readException) {
    readException.printStackTrace();
}           

23
投票

在Java 7中,你可以这样做......

try (BufferedReader r = new BufferedReader(...)){
     String inLine;
     while ((inLine = r.readLine()) != null) {
          System.out.println(inLine);
     }
} catch(IOException e) {
   //handle exception
}
  • 在try块中声明变量需要它实现AutoCloseable
  • 在try块中声明变量也会将其范围限制为try块。
  • try块中声明的任何变量将在try块退出时自动调用close()

它被称为Try with resources statement


8
投票

是的,它很笨拙,丑陋和令人困惑。一种可能的解决方案是使用Commons IO,它提供closeQuietly方法。

在本页右侧的“相关”列中有许多问题实际上是重复的,我建议仔细研究这些问题来解决这个问题。


5
投票

就像提到Commons IO库的答案一样,Google Guava Libraries对于java.io.Closeable这样的东西有一个类似的帮助方法。该课程是com.google.common.io.Closeables。您正在寻找的功能同样命名为Commons IO:closeQuietly()。

或者你可以自己滚动来关闭这样的一堆:Closeables.close(closeable1,closeable2,closeable3,...):

import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;

public class Closeables {
  public Map<Closeable, Exception> close(Closeable... closeables) {

  HashMap<Closeable, Exception> exceptions = null;

  for (Closeable closeable : closeables) {
    try {
      if(closeable != null) closeable.close();
    } catch (Exception e) {
        if (exceptions == null) {
          exceptions = new HashMap<Closeable, Exception>();
        }
        exceptions.put(closeable, e);
      }
    }

    return exceptions;
  }
}

这甚至会返回抛出的任何异常的映射,如果没有则返回null。


2
投票

你最终的方法是正确的。如果您在finally块中调用的代码可能会抛出异常,请确保您要么处理它,要么记录它。永远不要让它冒出finally块。

在catch区块中,您正在吞咽异常 - 这是不正确的。

谢谢...


0
投票
public void enumerateBar() throws SQLException {
    Statement statement = null;
    ResultSet resultSet = null;
    Connection connection = getConnection();
    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery("SELECT * FROM Bar");
        // Use resultSet
    }
    finally {
        try {
            if (resultSet != null)
                resultSet.close();
        }
        finally {
            try {
                if (statement != null)
                    statement.close();
            }
            finally {
                connection.close();
            }
        }
    }
}

private Connection getConnection() {
    return null;
}

source。这个样本对我很有用。


0
投票

我在你的代码中注意到的第一件事是你的代码中缺少大括号{}。你还需要将r的值初始化为null,因此你需要首先将null值传递给object,这样如果你写的条件可以执行not null条件检查并让你关闭流。

© www.soinside.com 2019 - 2024. All rights reserved.