gpt4 book ai didi

java - 如何使在 try block 中声明的最终变量在 catch/finally block 中使用?

转载 作者:行者123 更新时间:2023-12-02 11:06:41 25 4
gpt4 key购买 nike

public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
try {
final FileReader fileReader = new FileReader(inputFile);
final BufferedReader bufferedReader = new BufferedReader(fileReader);
final StringBuffer content = new StringBuffer();
while((tempLine=bufferedReader.readLine())!=null) {
content.append(tempLine);
content.append(System.getProperty("line.separator"));
}
}
catch(FileNotFoundException e) {
log.log(Level.WARNING, "File not found", e);
}
catch (IOException e) {
log.log(Level.WARNING, "Couldn't Read file", e);
}
finally {
bufferedReader.close();
fileReader.close();
}
return content;
}

在try block 中声明为final的变量fileReader和bufferedReader不能在finally block 中使用。我不能在 try block 之外声明它们,因为它们可能会引发异常。我也希望变量是最终的。

最佳答案

如果您至少使用 Java 7,则可以使用 try-with-resources Statement关闭您的资源。代码如下:

public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
try (final FileReader fileReader = new FileReader(inputFile)) {
try (final BufferedReader bufferedReader = new BufferedReader(fileReader)) {
final StringBuffer content = new StringBuffer();
while((tempLine=bufferedReader.readLine())!=null) {
content.append(tempLine);
content.append(System.getProperty("line.separator"));
}

return content;
}
} catch (FileNotFoundException e) {
log.log(Level.WARNING, "File not found", e);
} catch (IOException e) {
log.log(Level.WARNING, "Couldn't Read file", e);
}
// return null or throw exception;
}

关于java - 如何使在 try block 中声明的最终变量在 catch/finally block 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50909093/

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