本文介绍了while 循环中的 ObjectInputStream readObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to read from ObjectInputStream in while loop which will terminate by exception thrown by socket timeout socket.setSoTimeout(4000);

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

推荐答案

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

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

When you say 'not working', what you really mean is 'not compiling', for reasons that are stated in the compiler message: Object isn't a boolean expression, and you can't declare a variable in a while condition.

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

However the code isn't valid anyway. The correct way to read to end of stream of an arbitrary ObjectInputStream is catch EOFException, for example as follows:

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
}

请注意,注释中关于测试 nullreadObject() 返回值的建议是正确的.如果您编写了 null,它只会返回 null.

Note that the suggestion in comments to test the readObject() return value for null is not correct. It will only return null if you wrote a null.

这篇关于while 循环中的 ObjectInputStream readObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 18:54