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

后端 未结 7 1329
独厮守ぢ
独厮守ぢ 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:26

    It's complaining about the symbol not being there because it's not. It's in the try block. If you want to refer to fileIn, you'll need to declare it outside the try.

    However, it really sounds like you'd want to place the close in a finally block instead: you should close the file regardless of success or failure before returning.

    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); 
        }finally{
            if(fileIn != null) fileIn.close();
        }
        return fileArrayList;
    }
    

提交回复
热议问题