gpt4 book ai didi

java - 为什么我需要在 BufferedReader 中捕获 close() 异常,但在 PrintWriter 中不需要?

转载 作者:行者123 更新时间:2023-12-02 10:54:31 30 4
gpt4 key购买 nike

我有一个简单的文件读写功能。

private void WriteToFile(String filename, String val) {
PrintWriter outStream = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
outStream = new PrintWriter(new OutputStreamWriter(fos));
outStream.print(val);
outStream.close();
} catch (Exception e) {
if (outStream != null) {
outStream.close();
}
}
}

private String ReadFile(String filename) {
String output = "";
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
output = br.readLine();
br.close();
} catch (Exception e) {
if (br != null) {
br.close();
}
}

return output;
}

构建时我得到:

unreported exception java.io.IOException; must be caught or declared to be thrown
br.close();
^

为什么我需要捕获 br.close 但它不会提示 WriteToFile 的 close()?

最佳答案

取自java.io.PrintWriter的源代码:

public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
}

IOException 被 PrintWriter 中的 close() 方法吞噬

来自java.io.BufferedReader的源代码:

public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
}

BufferedReader 抛出 IOException。

这应该可以回答你的问题。

关于java - 为什么我需要在 BufferedReader 中捕获 close() 异常,但在 PrintWriter 中不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954021/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com