Close a Scanner linked to System.in

JavaNewbie_M107 picture JavaNewbie_M107 · Jan 3, 2013 · Viewed 14.9k times · Source

I have a Scanner linked to System.in. Now, after using the Scanner, I should close it, as it is bad coding practice to leave it open. But, if I close the Scanner, I will also be closing System.in! Can anyone tell me how I can close the Scanner without closing System.in (if there is any way).

Answer

Peter Lawrey picture Peter Lawrey · Jan 3, 2013

The simplest thing is to not close Scanner if you don't want to close the underlying stream.

Ideally you should create just one Scanner which you use for the life of the program. In any case, it appears you don't have a good reason to close it.