Close file in finally block doesn't work

后端 未结 3 564
不思量自难忘°
不思量自难忘° 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:23

    You have a problem with your scopes. If you really want to use that syntax you should fix it like this:

    FileReader fr = null;
    try {
        fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
    } catch (FileNotFoundException fnf) {
        fnf.printStackTrace();
    } finally {
        if( fr != null)
           fr.close();
    }
    

    that way, fr will exist in the finally's block scope.

提交回复
热议问题