我有类似以下内容:
public class X extends Thread{
BufferedInputStream in = (BufferedInputStream) System.in;
public void run() {
while (true) {
try {
while (in.available() > 0) {
// interesting stuff here
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
...这在很大程度上有效,但是有时我会开始在 stderr 中看到以下内容(一旦发生似乎会不断重复 - 我猜一旦开始发生应用程序最终会崩溃):
java.io.IOException: Illegal seek
at java.io.FileInputStream.available(Native Method)
at java.io.BufferedInputStream.available(BufferedInputStream.java:381)
at compactable.sqlpp.X.run(X.java:40)
...我不知道是什么原因造成的。老实说难住了。群众对于如何发生这种情况有什么想法吗?
感谢收到任何/所有有用的建议:-)
最佳答案
如果流已关闭,您可以获得可用的 IOException 调用。
此外,available()不会告诉您流还剩多少内容需要读取,或者流是否为空,它只告诉您可以在不阻塞的情况下读取多少内容(基本上是等待更多内容放入流中)。您想要的是读取直到读取返回-1。
int c;
while ( (c = in.read()) != -1 ) {
// do stuff
}
或
int readLength;
byte[] buffer = new byte[1024];
while ( (length = in.read(buffer) != -1) {
// do stuff with buffer, it now has bytes in buffer[0] to buffer[readLength-1]
}
关于java - System.in available() 调用给出 "Illegal seek",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11618662/