Close Scanner without closing System.in

deepy picture deepy · Feb 19, 2013 · Viewed 6.9k times · Source

I'm trying to re-factor a large and frequently used part of my application into separate methods to make it easier to maintain.

Some of these methods asks the user for input and does input validation, so I've used a Scanner and System.in But when I close my Scanner I also close System.in

So my question is, can I only prevent System.in being closed by shielding it with CloseShieldInputStream or should I just start passing a Scanner to the methods?

Answer

Raúl Salinas-Monteagudo picture Raúl Salinas-Monteagudo · Nov 11, 2013

Simply use a custom FilterInputStream instead of System.in:

new FilterInputStream(System.in) {
    @Override
    public void close() throws IOException {
        //don't close System.in! 
    }
}