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).
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.
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.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With