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

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

java - Resource Leak Error

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...