使用try-with-resources或关闭此"BufferedReader"在“最后"条款 [英] Use try-with-resources or close this "BufferedReader" in a "finally" clause
本文介绍了使用try-with-resources或关闭此"BufferedReader"在“最后"条款的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一直在寻找解决此问题的方法.阅读所有先前的答案,但没有一个帮助我.SonarQube可能有任何错误吗?
Been looking for a way to fix this issue. Read all the previous answers but none helped me out. Could it be any error with SonarQube?
public class Br {
public String loader(String FilePath){
BufferedReader br;
String str = null;
StringBuilder strb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f){
System.out.println(FilePath+" does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
}
推荐答案
您没有调用 br.close()
,这意味着冒着资源泄漏的危险.为了可靠地关闭 BufferedReader
,您有两个选择:
You are not calling br.close()
which means risking a resource leak. In order to reliably close the BufferedReader
, you have two options:
使用 finally
块:
using a finally
block:
public String loader(String FilePath) {
// initialize the reader with null
BufferedReader br = null;
String str = null;
StringBuilder strb = new StringBuilder();
try {
// really initialize it inside the try block
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
// this block will be executed in every case, success or caught exception
if (br != null) {
// again, a resource is involved, so try-catch another time
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strb.toString();
}
使用 try
-with-resources语句:
using a try
-with-resources statement:
public String loader(String FilePath) {
String str = null;
StringBuilder strb = new StringBuilder();
// the following line means the try block takes care of closing the resource
try (BufferedReader br = new BufferedReader(new FileReader(FilePath))) {
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
这篇关于使用try-with-resources或关闭此"BufferedReader"在“最后"条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文