关闭扫描仪而不关闭System.in

我正在尝试将我的应用程序中一个经常使用的大部分内容重新分解为单独的方法,以使其更易于维护。

其中一些方法要求用户输入并进行输入validation,所以我使用了扫描仪和System.in但是当我关闭扫描仪时我也关闭了System.in

所以我的问题是,我是否可以通过使用CloseShieldInputStream屏蔽它来阻止System.in关闭,还是我应该开始将Scanner传递给方法?

您可以通过实现自定义装饰器来忽略关闭。

public class UnClosableDecorator extends InputStream { private final InputStream inputStream; public UnClosableDecorator(InputStream inputStream) { this.inputStream = inputStream; } @Override public int read() throws IOException { return inputStream.read(); } @Override public int read(byte[] b) throws IOException { return inputStream.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return inputStream.read(b, off, len); } @Override public long skip(long n) throws IOException { return inputStream.skip(n); } @Override public int available() throws IOException { return inputStream.available(); } @Override public synchronized void mark(int readlimit) { inputStream.mark(readlimit); } @Override public synchronized void reset() throws IOException { inputStream.reset(); } @Override public boolean markSupported() { return inputStream.markSupported(); } @Override public void close() throws IOException { //do nothing } } 

并在主要使用它

 public static void main(String[] args) throws Exception { System.setIn(new UnClosableDecorator(System.in)); } 

只需使用自定义FilterInputStream而不是System.in:

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

你可以让它没有关闭它,只需将保持变量设置为null