当我在同一应用程序中通过键盘获取多个数据时,此代码会出现错误,它会出现 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/