java关闭文件,在java中捕获IOException后如何关闭文件?

All,

I am trying to ensure that a file I have open with BufferedReader is closed when I catch an IOException, but it appears as if my BufferedReader object is out of scope in the catch block.

public static ArrayList readFiletoArrayList(String fileName, ArrayList fileArrayList)

{

fileArrayList.removeAll(fileArrayList);

try {

//open the file for reading

BufferedReader fileIn = new BufferedReader(new FileReader(fileName));

// add line by line to array list, until end of file is reached

// when buffered reader returns null (todo).

while(true){

fileArrayList.add(fileIn.readLine());

}

}catch(IOException e){

fileArrayList.removeAll(fileArrayList);

fileIn.close();

return fileArrayList; //returned empty. Dealt with in calling code.

}

}

Netbeans complains that it "cannot find symbol fileIn" in the catch block, but I want to ensure that in the case of an IOException that the Reader gets closed. How can I do that without the ugliness of a second try/catch construct around the first?

Any tips or pointers as to best practise in this situation is appreciated,

解决方案

BufferedReader fileIn = null;

try {

fileIn = new BufferedReader(new FileReader(filename));

//etc.

} catch(IOException e) {

fileArrayList.removeall(fileArrayList);

} finally {

try {

if (fileIn != null) fileIn.close();

} catch (IOException io) {

//log exception here

}

}

return fileArrayList;

A few things about the above code:

close should be in a finally, otherwise it won't get closed when the code completes normally, or if some other exception is thrown besides IOException.

Typically you have a static utility method to close a resource like that so that it checks for null and catches any exceptions (which you never want to do anything about other than log in this context).

The return belongs after the try so that both the main-line code and the exception catching have a return method without redundancy.

If you put the return inside the finally, it would generate a compiler warning.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值