Object中的ObjectInputStream

Object中的ObjectInputStream

本文介绍了Object中的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 表达式,并且您不能在中声明变量虽然条件。

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
}

请注意评论中的建议以测试 readObject() null的返回值 正确。如果你写了 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.

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

08-06 02:53