Close file in finally block doesn't work

夙愿已清 提交于 2020-01-01 04:36:08

问题


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

The fr.close() shows an error:

fr cannot be resolved

I had read that closing a file in the finally block is a good practice.
What is that am doing wrong?


回答1:


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()




回答2:


Now finally block is not needed,

try (FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);){

    String line = null;

    }

} catch(FileNotFoundException fnf) {
    fnf.printStackTrace();
} 

now automatically close your readers




回答3:


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.



来源:https://stackoverflow.com/questions/8981589/close-file-in-finally-block-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!