资源泄漏 java,Java - 关闭扫描程序和资源泄漏

I'm learning Java and working on some projects for fun. One issue that I have run in to is that when I use a Scanner object Eclipse warns me that:

Resource Leak: 'scan' is never closed.

So, I added a scan.close(); at the end of my code and that takes care of the warning.

The problem comes in because I have other classes in the same package that also use scanner objects and and Eclipse tells me to close scanner in those classes respectively. However, when I do that it seems like it closes ALL of the scanner objects and I get errors during run time.

Here is an example of what causes the error:

import java.util.Scanner;

public class test2 {

public static void main(String [] args) {

Scanner scan = new Scanner(System.in);

int test = 0;

do {

//Do stuff

test = scan.nextInt();

System.out.println(test);

scanTest scanTest = new scanTest();

scanTest.test();

} while (test != 0);

scan.close();

}

}

import java.util.Scanner;

public class scanTest {

public void test() {

Scanner scanner = new Scanner(System.in);

int blah = scanner.nextInt();

System.out.println(blah);

scanner.close();

}

}

After scanner is closed in the scanTest class and the do loop in test2 is entered again an error occurs at the line test = scan.nextInt();

I tried moving the creation of the scanner object into the do loop just to make a new object every time as well but the error still occurs.

Not sure why this is happening or how I can make sure all my I/O objects are closed out without running into problems.

One post I came across mentioned that when System.in is closed I cannot be re-opened. If this is the case would I just need to make sure a scanner object with System.in is closed at the very end of the program and @suppress all of the other scanner warnings in other classes? Or would that still leave all those scanner objects open (bad)?

解决方案

Yes, when you close a scanner you will be closing the underlying stream (in this case System.in). To avoid this, either create a global variable of scanner which can be used by all classes or have a central point for shutting down the scanner (just before the program exits would be ideal)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值