java 错误 IOException

标签 java ioexception

当我在同一应用程序中通过键盘获取多个数据时,此代码会出现错误,它会出现 IOException 错误;

离开 do while 时出错

我不知道他为什么会犯这种错误。

 public static String datoString() {
// Entorno:
    BufferedReader br;

    String frase;
    boolean esCorrecto;
    //Algoritmo
    frase=null;
    br = new BufferedReader(new InputStreamReader(System.in));
    try {
        do {

            System.out.println("Introduce una cadena");
            frase = br.readLine();
            esCorrecto = true;


        } while (!esCorrecto);

    } catch (IOException ioe) {
        System.err.println("Error I/O");
    }
    try {
        br.close();
    } catch (IOException ioe2) {
        ioe2.printStackTrace();
    }//Fin try


    return frase;

}

最佳答案

通过这样做

 br.close();

你实际上正在这样做

System.in.close();

因为 BufferedReader 关闭底层流。

这使得System.in流不再可用。 您需要做的是做一些小技巧来防止 System.in 关闭。为此,您可以使用以下包装器

public class ShieldedInputStream extends InputStream {

    InputStream source;

    public ShieldedInputStream(InputStream source) {
        this.source = source;
    }

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

    @Override
    public int read(byte[] b) throws IOException {
        return source.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return source.read(b, off, len);
    }

    @Override
    public long skip(long n) throws IOException {
        return source.skip(n);
    }

    @Override
    public int available() throws IOException {
        return source.available();
    }

    @Override
    public void close() throws IOException {
//        source.close(); // We dont awant to close it!
    }

    @Override
    public void mark(int readlimit) {
        source.mark(readlimit);
    }

    @Override
    public void reset() throws IOException {
        source.reset();
    }

    @Override
    public boolean markSupported() {
        return source.markSupported();
    }
}

像这样使用它

br = new BufferedReader(new InputStreamReader(new ShieldedInputStream(System.in)));

这样您就可以防止 System.in 关闭,但仍然允许您通过关闭 BufferedReader 来释放资源

关于java 错误 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078885/

相关文章:

c# - 复制文件时如何防止此 System.IO.IOException?

wpf - 删除窗口的背景图像 WPF

java - I/O 套接字错误 (Java)

java - 我在服务器套接字上接受客户端连接时捕获了 IOException。现在怎么办?

java - 什么会在 Java 中引发 IOException?

java - 创建了我自己的二分搜索版本,不明白为什么它比常规方法更快?

java - 如果在配置文件内,则仅执行 Maven 插件

java - TestNG 访问 @BeforeSuite 中的 ISuite

java - 如何在 java 应用程序和 adobe air 应用程序之间传递消息?

java - 如何在按键时重置处理 Canvas ?