while 循环中的 ObjectInputStream readObject

N K*_*mar 3 java compiler-errors objectinputstream

是否可以从ObjectInputStreamwhile 循环中读取,该循环将因套接字超时引发的异常而终止socket.setSoTimeout(4000);

while(Object obj = ois.readObject()) {  <-- Not Working
//do something with object    
}
Run Code Online (Sandbox Code Playgroud)

use*_*421 6

while(Object obj = ois.readObject()) {  <-- Not Working
//do something with object    
}
Run Code Online (Sandbox Code Playgroud)

当您说“不工作”时,您真正的意思是“不编译”,原因在编译器消息中说明:Object不是boolean表达式,并且您不能在while条件中声明变量。

但是无论如何代码都无效。读取任意流末尾的正确方法ObjectInputStream是 catch EOFException,例如如下:

try
{
    for (;;)
    {
        Object object = in.readObject();
        // ...
    }
}
catch (SocketTimeoutException exc)
{
    // you got the timeout
}
catch (EOFException exc)
{
    // end of stream
}
catch (IOException exc)
{
    // some other I/O error: print it, log it, etc.
    exc.printStackTrace(); // for example
}
Run Code Online (Sandbox Code Playgroud)

请注意,在意见建议,以测试readObject()返回值null正确的。只有null当你写了一个null.