Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a Scanner linked to System.in

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).

like image 959
JavaNewbie_M107 Avatar asked Jan 03 '13 16:01

JavaNewbie_M107


People also ask

Should you close System in Scanner?

It is recommended to always close the Scanner when we are reading a file. It ensures that no input or output stream is opened, which is not in use. The following example shows how we can read a string from the file and then close the scanner once the operation has been done.

How do you close a Scanner method?

close() method closes this scanner. If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

What does closing a Scanner do?

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Do I need to close Scanner in Java?

If you do not close the Scanner then Java will not garbage collect the Scanner object and you will have a memory leak in your program: void close(): closes the Scanner and allows Java to reclaim the Scanner's memory. You cannot re-use a Scanner so you should get rid of it as soon as you exhaust its input.


2 Answers

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.

like image 78
Peter Lawrey Avatar answered Oct 16 '22 15:10

Peter Lawrey


One option is to wrap your System.in stream in a CloseShieldInputStream that prevents it from being closed. Your reader would then use the CloseShieldInputStream rather than the raw System.in stream.

Here is the API for the class: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html

like image 20
paul jerman Avatar answered Oct 16 '22 15:10

paul jerman