java try finally块以关闭流 [英] java try finally block to close stream

查看:34
本文介绍了java try finally块以关闭流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally block in order to close the stream. Is that the right way to do it? It seems a bit clunky.

代码如下:

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


}

推荐答案

看起来有点笨重.

It seems a bit clunky.

是的.至少 java7 的资源尝试修复了这个问题.

It is. At least java7's try with resources fixes that.

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

Pre java7 you can make a closeStream function that swallows it:

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

或者把 try...finally 放在 try catch 里面:

Or put the try...finally inside the 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();
}

它更冗长,finally 中的异常将在 try 中隐藏一个,但在语义上更接近 try-with-resources 在 Java 7 中引入.

It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.

这篇关于java try finally块以关闭流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆