How do I close a file after catching an IOException in java?

后端 未结 7 1141
独厮守ぢ
独厮守ぢ 2021-01-05 08:07

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 o

7条回答
  •  被撕碎了的回忆
    2021-01-05 08:32

    Move the declaration out of the try block:

    public static ArrayList readFiletoArrayList(String fileName, ArrayList fileArrayList)
    {
        fileArrayList.removeAll(fileArrayList);
    
        BufferedReader fileIn = null;
        try {
            //open the file for reading
            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. 
        }
    }
    

    But, you'll still need to be careful that fileIn was actually initialized before trying to close it:

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

提交回复
热议问题