Resource Leak Error

前端 未结 4 2030
借酒劲吻你
借酒劲吻你 2020-12-21 13:05

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 \"R

4条回答
  •  一向
    一向 (楼主)
    2020-12-21 13:55

    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.

提交回复
热议问题