finally中关闭资源

时间:2022-06-21 17:51:20

对finally中关闭资源是否还要使用try...catch老是感到迷惑,现在存个例子,省的忘了

 public StringBuilder readTxtFile(File file){
StringBuilder sBuilder = new StringBuilder();
InputStreamReader isr = null;
BufferedReader br = null;
try {
if (file.isFile() && file.exists()) {
isr = new InputStreamReader(new FileInputStream(file), "GBK");
br = new BufferedReader(isr);
String line = null; while ((line = br.readLine()) != null) {
System.out.println(line);
sBuilder.append(line);
}
} else {
logger.info("文件不存在!");
}
} catch (Exception e) {
logger.info("文件读取错误!");
} finally {
// 关闭流
try {
if(isr != null) {
isr.close();
logger.info("isr已经成功关闭!");
}
if(br != null){
br.close();
logger.info("br已经成功关闭!");
}
} catch(Exception e) {
e.printStackTrace();
}
}
return sBuilder;
37 }