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块中声明为final的变量fileReader和bufferedReader不能在finally块中使用。我无法在try块之外声明它们,因为它们可能会引发异常。我也希望变量也是最终的。
最佳答案
从Java 7开始,您可以编写如下代码:
public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
final StringBuffer content = new StringBuffer();
try (final FileReader fileReader = new FileReader(inputFile);
final BufferedReader bufferedReader = new BufferedReader(fileReader)){
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);
}
return content;
}
在这里
fileReader
和bufferedReader
被隐式关闭。