Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

What am I doing wrong?

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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
551 views
Welcome To Ask or Share your Answers For Others

1 Answer

After finishing using the scanner, you must close with the close method:

scanner.close();

The reason why you must close it is because the Scanner class implements the Closeable interface. Straight from the API:

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).

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();
        }
    }

Read more about Scanner from the API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...