在java中捕获IOException后如何关闭文件? [英] How do I close a file after catching an IOException in java?
问题描述
全部
我正在尝试确保使用BufferedReader打开的文件在我捕获IOException时被关闭,但是看起来我的BufferedReader对象是超出范围的catch块。
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抱怨说找不到符号fileIn catch块,但是我想确保在IOException的情况下,Reader被关闭。如果没有第一次尝试/捕获构造的丑陋,我该怎么做?
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?
在这种情况下,有关最佳做法的任何提示或指针, p>
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应该在一个finally中,否则当代码正常完成时,或者除了IOException之外还会抛出一些其他异常,它不会被关闭。
- 通常,您有一个静态实用程序方法来关闭这样的资源,以便它检查null并捕获任何异常(除了此上下文之外,您不需要执行任何操作)
- 返回属性在尝试之后,所以主线代码和异常捕获都有一个没有冗余的返回方法。
- 如果将return返回到finally中,它将生成一个编译器警告。
- 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.
这篇关于在java中捕获IOException后如何关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!