资源泄漏错误 [英] Resource Leak Error
问题描述
晚上全部。我是使用Java编程的完全初学者,我正在学习扫描程序,但是当我在Eclipse中输入这个基本代码时,我收到一条消息资源泄漏:'扫描程序'永远不会关闭。
Evening all. I am a complete beginner to programming with Java, and I am learning about "Scanner", but when I type this basic code into Eclipse, I get a message saying "Resource leak:'scanner' is never closed.
我做错了什么?
package inputting;
import java.util.Scanner;
public class Input {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
}
}
推荐答案
使用扫描仪
后,必须以关闭$结束c $ c>方法:
scanner.close();
你必须关闭它的原因是因为 Scanner
类实现了可关闭界面。直接来自t他是API:
The reason why you must close it is because the Scanner
class implements the Closeable interface. Straight from the API:
A Closeable是可以关闭的数据的来源或目的地。调用
close方法来释放对象为
持有的资源(例如打开文件)。
A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).
基本上,如果您从未关闭 Scanner
,那么程序将继续寻求输入并保持资源。这是一个真正的简单示例:
Essentially, if you never close the Scanner
, then the program will continue to seek for input and keep hold of resources. Here is a really simple example:
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
while (scanner.hasNext()) {
System.out.println(scanner.next());
//do whatever you need here
}
} finally {
if (scanner != null) {
scanner.close();
}
}
了解更多关于扫描仪<来自 API 的/ code> 。
Read more about Scanner
from the API.
这篇关于资源泄漏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!