我正在使用Eclipse,并执行下面的功能,碰巧我打开了一个Scanner,然后,最后我关闭了它,但Eclipse一直说它没有关闭“资源泄漏:'扫描仪' 没有关闭”。 我可以通过尝试使用资源来做到这一点,警告消失了,但我想了解为什么我在这里尝试的方式不起作用
private void follow(String userID) {
if(!(new File("../users/"+userID+"/")).exists()){
System.out.println("User especificado nao existe");
return;
}
File list = new File("../users/"+userID+"/followers.txt");
try {
list.createNewFile();
Scanner scanner = new Scanner(list);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.equals(clientID)){
System.out.println("Cliente ja segue este user");
return;
}
}
PrintWriter out = new PrintWriter(new FileWriter(list, true));
out.append(clientID+"\n");
out.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
#createNewFile()
可以在您到达 close()
语句之前抛出 IOException,从而阻止它被执行。
答案 1 :(得分:0)
将 $results = (new AppendablePaginator($db_query->paginate($num_of_results))->modelAppend([
'ProjectDescription',
'FileCountLabel'
]);
放在 finally 语句中:
out.close()
finally {
out.close();
}
的作用是,即使抛出错误,其中的任何代码也会被执行。
答案 2 :(得分:0)
Scanner 实现了 AutoCloseable;你可以使用 try-with-resources
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html