Resource leak: 'in' is never closed

2019-01-03 08:39发布

Why does Eclipse give me the warming "Resource leak: 'in' is never closed" in the following code?

public void readShapeData() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the width of the Rectangle: ");
        width = in.nextDouble();
        System.out.println("Enter the height of the Rectangle: ");
        height = in.nextDouble();

13条回答
甜甜的少女心
2楼-- · 2019-01-03 09:13

Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add in.close().

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-03 09:16
private static Scanner in;

I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.

查看更多
戒情不戒烟
4楼-- · 2019-01-03 09:20
Scanner sc = new Scanner(System.in);

//do stuff with sc

sc.close();//write at end of code.
查看更多
再贱就再见
5楼-- · 2019-01-03 09:20
in.close();
scannerObject.close(); 

It will close Scanner and shut the warning.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-03 09:21

The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.

查看更多
干净又极端
7楼-- · 2019-01-03 09:22

You need call in.close(), in a finally block to ensure it occurs.

From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):

Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.

The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy.

...

The compiler will flag [violations] with "Resource leak: 'stream' is never closed".

Full explanation here.

查看更多
登录 后发表回答