从服务器(不是文件)读取对象时发生Java EOFEException

从服务器(不是文件)读取对象时发生Java EOFEException,java,networking,eofexception,Java,Networking,Eofexception,因此,我向客户机写入一个对象,如下所示: ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream()); out.writeObject(args); out.close(); 并在客户端接收对象,如下所示: ObjectInputStream in = new ObjectInputStream(connection.getInputStream()); Object objIn; while(true)

因此,我向客户机写入一个对象,如下所示:

ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(args);
out.close();
并在客户端接收对象,如下所示:

ObjectInputStream in = new ObjectInputStream(connection.getInputStream());

Object objIn;
while(true) {
    if((objIn = in.readObject()) != null) {
        //work with obj
    }
}
我从不在客户端创建输出流,也从不在服务器端创建输入流

此外,我发送的对象是可序列化的

谢谢你的帮助

编辑:这个问题的“重复”不能帮助我回答我的问题,所以这个问题不是重复的

while(true) {
    if((objIn = in.readObject()) != null) {
        //work with obj
    }
}
问:为什么要测试
null
?您是否计划发送
null
?因为那是你唯一能得到的机会。 A.因为您认为
readObject()
在流的末尾返回
null
。尽管您遗漏了
中断
,但它将逃脱无限循环

没有。它抛出
EOFEException.
因此循环应该如下所示:

try
{
    while(true) {
        objIn = in.readObject();
        //work with obj
    }
}
catch (EOFException exc)
{
    // end of stream
}
finally
{
    in.close();
}

假设从连接对象读取输入流时收到异常

如果您在上述输入流代码之前已经调用了
连接.getInputStream()
,您将收到一个EOF异常。因为连接对象中的输入流已被使用

解决此问题的一个方法是将输入流的内容写入随机访问文件中,因为它们使您能够遍历该文件

public static RandomAccessFile toRandomAccessFile(InputStream is, File tempFile) throws IOException
    {
        RandomAccessFile raf = new RandomAccessFile(tempFile, "rwd");
        byte[] buffer = new byte[2048];
        int    tmp    = 0;
        while ((tmp = is.read(buffer)) != -1)
        {
            raf.write(buffer, 0, tmp);
        }
        raf.seek(0);
        return raf;
    }
以后,您始终可以按如下方式读取该文件

public static InputStream toInputStream(RandomAccessFile file) throws IOException
    {
        file.seek(0);    /// read from the start of the file 
        InputStream inputStream = Channels.newInputStream(file.getChannel());
        return inputStream;
    }

您在何处收到EOF异常?我在调用.readObject()时收到异常。副本包含与我在此处给出的答案完全相同的答案。调用
getInputStream()
不会消耗任何东西。我将把什么作为
tempFile
参数?我的程序与
文件
无关。我从servlet发送的对象不是
文件
。我要实例化什么构造函数?@LucasBaizer忘了它吧,它毫无意义。“相关主题”与你的答案没有任何关系。