小编Dim*_*Dom的帖子

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

所有,

我试图确保在捕获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被关闭.如果没有第一次尝试/捕获构造的丑陋,我怎么能这样做呢?

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

java exception-handling try-catch ioexception bufferedreader

7
推荐指数
1
解决办法
2万
查看次数