所有,
我试图确保在捕获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. } }
Netbeans抱怨说它在catch块中“找不到符号fileIn”,但是我想确保在发生IOException的情况下,Reader被关闭。在没有围绕第一个try / catch构造的丑陋的情况下,我该怎么做呢?
在这种情况下,有关最佳做法的任何提示或建议,
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;
关于上述代码的几件事: