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

dee*_*epy 12 java system.in java.util.scanner

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

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

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

Raú*_*udo 18

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

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

  • 比接受的答案更简单!谢谢. (4认同)
  • 这几乎是公共'[CloseShieldInputStream](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html)的作用,如果你最终这个您可能希望再次了解您的软件设计.除非您正在使用第三方解决方案,否则不应该需要这样的解决方案.(适用于此处的所有答案) (2认同)

nku*_*har 3

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 main 中使用它

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

  • 我怀疑我应该开始传递扫描仪,这似乎是最不痛苦的方式。 (2认同)