java尝试最后阻止关闭流

2022-09-01 05:36:46

我想在最后的块中关闭我的流,但它抛出了一个,所以似乎我必须在我的块中嵌套另一个块才能关闭流。这是正确的方法吗?这似乎有点笨拙。IOExceptiontryfinally

代码如下:

 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();
        }
    }


}

答案 1

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

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();
}           

答案 2

这似乎有点笨拙。

是的。至少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{
    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();
}

它更冗长,最后中的异常将在尝试中隐藏一个,但它在语义上更接近Java 7中引入的资源尝试