我试图用java编写一个方法,在这里我从一个文件中获取一些信息,并查看该文件是否包含用户查找的信息。但是,对于我所呈现的代码,eclipse标志着我在行“返回真”中有一个资源泄漏;并且"br = never (Fr);“永远不会关闭,尽管我在程序结束时使用了close()方法。显然我漏掉了什么。有人能帮我弄清楚发生了什么吗?非常感谢,提前!
import java.io.*;
class Help{
String helpfile;
Help(String fname){
helpfile = fname;
}
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
}
catch(FileNotFoundException e){
System.out.println(e);
return false;
}
try{
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
}
catch(IOException e){
System.out.println(e);
return false;
}
try{
br.close();
}
catch(IOException e){
System.out.println(e);
}
return false;
}
}发布于 2014-08-13 21:32:46
问题是,在程序有机会关闭资源之前,您将返回。有两种方法可以解决这个问题:
数字2通常是一种更被接受的做法,因为如果将来添加更多的东西,那么仍然可以保证关闭资源(除非发生灾难性事件)。
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch(IOException e){
System.out.println(e);
return false;
} catch(FileNotFoundException e){
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch(IOException e){
System.out.println(e);
return false;
}
}
}发布于 2014-08-13 21:27:41
整个方法都有返回语句,但最后只有一个br.close()。在代码流中,可能会返回该方法,而br仍然处于打开状态。
您可能对使用try with resources感兴趣
try (
FileReader fr = new FileReader(helpfile);
BufferedReader br = new BufferedReader(fr)
)
{
//your code
}
catch (IOException e)
{
//error
}这样,就会自动在资源上为您调用close方法。
发布于 2014-08-13 21:27:30
您应该将对close()的调用放在一个finally块中。在当前状态下,由于要返回true或false,您的代码将永远不会到达最后的try/catch。
try {
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do {
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch (IOException e) {
System.out.println(e);
return false;
} catch (FileNotFoundException e) {
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
System.out.println(e);
}
}https://stackoverflow.com/questions/25296388
复制相似问题