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

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

问题描述

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



以下是代码:

  public void read(){
try {
r = new BufferedReader(new InputStreamReader(address.openStream()));
String inLine; ((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();





$ b $ div class =



$ b

这是一个笨蛋。至少java7的尝试资源修复。



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

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

或者把try ...终于在try catch里面:

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

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



$ b $ p
$ b

它更加冗长,在finally中会有一个例外,它在语义上更接近于引入的试用资源 Java 7。


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.

Here's the code:

 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.

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

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

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

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试试finally块关闭流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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