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

显示fr.close()错误:

fr 无法解决

我读过在 finally 块中关闭文件是一个好习惯。
那是什么做错了?

4

4 回答 4

30

该变量仅在块fr内具有范围。try它超出了 finally 块的范围。您需要在块之前声明它:try

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

这是一种非常常见的代码模式,因此最好记住它以备将来类似情况使用。

考虑从这个方法中抛出IOException- 打印跟踪跟踪对调用者不是很有帮助,而且你不需要嵌套的 try catchfr.close()

于 2012-01-24T03:17:00.910 回答
9

现在 finally 块是不需要的,

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

    String line = null;

    }

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

现在自动关闭你的读者

于 2012-01-24T03:21:05.243 回答
0

你的范围有问题。如果您真的想使用该语法,您应该像这样修复它:

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

这样,fr 将存在于 finally 的块范围内。

于 2012-01-24T03:27:03.227 回答
0
public static void main(String[] args) throws IOException{
        FileReader file1 = null;
        try{
            file1 = new FileReader("blaaa.txt");//this file does not exist
        }
        catch (FileNotFoundException e){}
        catch (IOException e)  {e.printStackTrace();}
        finally {
            try{file1.close();}
            catch (NullPointerException e){
            }
            finally {
                System.out.println("Thank you, please try again");
            }
        }
    }
于 2022-01-22T04:36:14.330 回答