为什么会显示错误:"资源泄漏:'键盘'从未关闭"?

时间:2018-06-14 05:42:02

标签: java eclipse input java.util.scanner

我最近在一台新计算机上安装了Eclipse,当我尝试编写此代码时,它给了我这个错误。我发誓,我已经写过这种类型的

Scanner keyboard = new Scanner(System.in) 
很多次,在我的旧电脑中,直到现在才发生这个错误。

import java.util.Scanner;
public class W1M1 {

public static void main(String[] args) {
    System.out.println("Hellow World");
    Scanner keyboard = new Scanner(System.in); //'keyboard' word shows this error
    System.out.println("Please enter your name: ");
    String userInput = keyboard.nextLine();
    System.out.println("Hello there, " + userInput + ".");
}

}

1 个答案:

答案 0 :(得分:0)

Scanner类实现Closable接口 - 即它打开一个资源,你应该自己调用close()方法,所以,一般来说,Eclipse做正确的事情,在这里发出警告。

但是,在这种特定情况下,#!/bin/bash if [ -z ${1+x} ]; then echo "No argument"; else echo "There is argument"; cd $1; fi for filename in $(ls) do if [ -f "$filename" ] then printf "$filename - file\n" fi if [ -d "$filename" ] then count=$(ls "$filename" | wc -l) printf "$filename - directory $count files\n" fi done keyboard,它引用Scanner - 标准输入描述符。你永远不应该自己关闭它,并且应该在这种情况下抑制Eclipse的警告。