java try finally block to close stream

2019-01-14 05:52发布

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


}

7条回答
\"骚年 ilove
2楼-- · 2019-01-14 06:44

Yes it is clunky, ugly and confusing. One possible solution is to use Commons IO which offers a closeQuietly method.

There's a number of questions in the "Related" column on the right hand of this page that are actually duplicates, I advise to look through these for some other ways of dealing with this issue.

查看更多
登录 后发表回答