Close file in finally block doesn't work

后端 未结 3 562
不思量自难忘°
不思量自难忘° 2021-02-07 11:53
try {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line = null;
} catch (FileNotFoundException fnf) {
    fnf.pri         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 12:05

    The variable fr only has scope within the try block. It is out of scope in the finally block. You need to declare it before the try block:

    FileReader fr = null;
    try {
        fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                // This is unrecoverable. Just report it and move on
                e.printStackTrace();
            }
        }
    }
    

    This is quite a common pattern of code, so it's good to remember it for future similar situations.

    Consider throwing IOException from this method - printing track traces isn't very helpful to callers, and you wouldn't need the nested try catch around fr.close()

提交回复
热议问题