我正在尝试将我的应用程序中一个经常使用的大部分内容重新分解为单独的方法,以使其更易于维护。
其中一些方法要求用户输入并进行输入验证,所以我使用了扫描仪和System.in但是当我关闭扫描仪时我也关闭了System.in
所以我的问题是,我是否可以通过使用CloseShieldInputStream屏蔽它来阻止System.in关闭,还是我应该开始将Scanner传递给方法?
发布于 2018-12-04 15:08:39
您可以通过实现自定义装饰器来忽略关闭。
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));
}
发布于 2018-12-04 15:37:50
只需使用自定义FilterInputStream而不是系统。
new FilterInputStream(System.in) {
@Override
public void close() throws IOException {
//don't close System.in!
}
}
https://stackoverflow.com/questions/-100006208
复制相似问题