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

Dim*_*Dom 7 java exception-handling try-catch ioexception bufferedreader

所有,

我试图确保在捕获IOException时关闭了我用BufferedReader打开的文件,但看起来好像我的BufferedReader对象超出了catch块的范围.

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. 
    }
}
Run Code Online (Sandbox Code Playgroud)

Netbeans抱怨它在catch块中"找不到符号fileIn",但是我想确保在IOException的情况下Reader被关闭.如果没有第一次尝试/捕获构造的丑陋,我怎么能这样做呢?

关于这种情况下的最佳实践的任何提示或指示表示赞赏,

Yis*_*hai 23

 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;
Run Code Online (Sandbox Code Playgroud)

关于上面代码的一些事情:

  • close应该在finally中,否则在代码正常完成时不会被关闭,或者除了IOException之外还抛出其他异常.
  • 通常,您有一个静态实用程序方法来关闭这样的资源,以便它检查null并捕获任何异常(除了在此上下文中登录之外,您永远不想做任何事情).
  • 返回属于try之后,因此主线代码和异常捕获都有一个没有冗余的返回方法.
  • 如果将返回值放在finally中,则会生成编译器警告.