我正在尝试将应用程序中一个经常使用的大部分重新组织为独立的方法,以便于维护。
其中一些方法需要用户输入并进行输入验证,因此我使用了Scanner和System.in。但是,当我关闭Scanner时,也会关闭System.in。
所以我的问题是,我只能通过CloseShieldInputStream来保护System.in不关闭,还是应该开始向这些方法传递Scanner?
我正在尝试将应用程序中一个经常使用的大部分重新组织为独立的方法,以便于维护。
其中一些方法需要用户输入并进行输入验证,因此我使用了Scanner和System.in。但是,当我关闭Scanner时,也会关闭System.in。
所以我的问题是,我只能通过CloseShieldInputStream来保护System.in不关闭,还是应该开始向这些方法传递Scanner?
只需使用自定义的FilterInputStream而不是System.in:
new FilterInputStream(System.in) {
@Override
public void close() throws IOException {
//don't close System.in!
}
}
Scanner
关闭时关闭 System.in
。 - deepypublic 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));
}
您可以不关闭它,只需将占位变量设置为null即可。
System.in
,则不要在Scanner上调用close()
。 - kaya3