如何关闭扫描仪,无需关闭底层System.in?(How to close a scanner wi

2019-10-20 19:13发布

如果我收一个扫描对象,使一个新的,并尝试读一些更多的投入,我得到NoSuchElementException例外。

我的代码工作正常,但它给了我一个警告,如果我不关闭扫描仪。 不过,如果我关闭它去除掉的警告,我也接近System.in ...我如何避免这种情况?

此外,是否有不关闭扫描仪的任何后果?

编辑:这是我的代码:

这是NameAddressExists()方法:

public void NameAddressExists() {
    System.out.println("Enter name");
    Scanner sc = new Scanner(System.in);
    String n = sc.next();
    System.out.println("Enter address");
    String a = sc.next();
    int flag = 0;
    for(int i = 0; i < count; i++) {
        if(array[i].name .equals(n) && array[i].address .equals(a)) {
            System.out.println("True");
            flag = 1;
        }
    }
    if(flag != 1) {
        new Agency(n, a);
    }
    sc.close();
}

这是PanNumberExists()方法:

public boolean PanNumberExists() {
    Scanner s = new Scanner(System.in);
    String n = "";
    System.out.println("Enter the 5 digits");
    try {
        n = s.nextLine();
    }catch(Exception e) {
        System.out.println(e);
    }finally {
        s.close();
    }
    if(n  .equals(this.PAN.subSequence(4,9))) {
        return true;
    }
    else {
        return false;
    }
}

这些方法是从下面的main()方法调用:

public static void main(String args[]) {
    Agency obj1 = new Agency("XYZ", "ABCD");
    Agency obj2 = new Agency("XYZ", "ABCDEFG", "+91083226852521", "ab 1234567", "abcd12345ab");
    // Agency obj3 = new Agency("XYZ", "TSRK", "36", "ab 1234567", "abcd12345ab");
    obj1.NameAddressExists();
    System.out.println(obj2.PanNumberExists());
}

正如你所看到的,我首先调用NameAddressExists()方法,在我打开,使用和关闭Scanner命名为“SC”。 这工作得很好,给我正确的输出。 接下来,我调用PanNumberExists()方法,在我打开另一个Scanner名为“S”,并尝试用它来从用户那里得到一些信息。 这是我收到的NoSuchElementException例外。 如果我离开了Scanner “SC”在我NameAddressExists open()方法的话,我没有得到这个错误。

Answer 1:

Scanner scan = new Scanner(new FilterInputStream(System.in) {
    @Override
    public void close() throws IOException {
        // do nothing here ! 
    }
});

或者,不理会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
    }
}

而且在使用中main()

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


Answer 2:

您可以使用Decorator模式,并创建自定义InputStream不能关闭,然后将它传递给Scanner

import java.io.IOException;
import java.io.InputStream;

public class PreventClosingInputStream extends InputStream {

    private InputStream inputStream;

    public PreventClosingInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public int read() throws IOException {
        return inputStream.read();
    }

    @Override
    public void close() throws IOException {
        // Don't call super.close();
    }

}

然后,在你的代码:

PreventClosingInputStream in = new PreventClosingInputStream(System.in);
Scanner s = new Scanner(in);
// ...
s.close(); // This will never close System.in as there is underlying PreventClosingInputStream with empty close() method

使用try-与资源:

try (PreventClosingInputStream in = new PreventClosingInputStream(System.in);
        Scanner s = new Scanner(in);) {
    // ...
    // resources will be automatically closed except of System.in
}


文章来源: How to close a scanner without closing the underlying System.in?