有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何识别ObjectInputStream是否有可用的对象?

试图标识序列化对象是否可用并使用socket接收它时,获取错误NullPointerException。如何确定ObjectInputStream是否有可用的对象? 首先,我尝试读取一个文本,然后尝试读取同一个socket Lot对象(),它可能不在那里

        public class ThreadIn extends Thread{
        BufferedReader in;
            PrintStream outConsole;
            Socket socket;
            ObjectInputStream ois;
            String str;
            Lot lot;
ThreadIn(BufferedReader input, PrintStream inOutput, Socket s){
        str = "";
        in= input;
        socket= s;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        outConsole = inOutput;

    }
    public void run() {

            while(!EXIT_THREAD){
            try {
        if(in.ready()){
            try {
                str= in.readLine();
                    Thread.sleep(100);
                } catch (IOException e) {
                EXIT_THREAD= true;
                break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                outConsole.println("Received:"+str);

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            try {
                if((Lot)ois.readObject() != null){      
                    lot = (Lot)ois.readObject(); 
                    if (lot!=null){outConsole.println(lot.toString());} 
                    outConsole.println((String)ois.readObject());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    }

共 (2) 个答案

  1. # 1 楼答案

    if((Lot)ois.readObject() != null)
    

    此部件本身从套接字读取对象。,因此,您正在代码中从套接字读取3倍的对象。如果套接字中只有一个或多个对象,则可以读取该对象并捕获异常!。 就像下面

     //..loop start
             try {
                    lot = (Lot)ois.readObject(); 
                 }
             catch (Exception e) 
               { 
    //      do some handling, skip the object! put a continue: or something
    
                }
        //do what ever you want to do with `lot`
    
        //..loop end
    

    现在,根据您的代码,您还没有初始化ObjectInputStream对象

    做一个ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

    如果您省略了这里的代码,那么是我的错误,否则也请初始化套接字

  2. # 2 楼答案

    根据其他答案,包括已删除的答案,您将调用readObject()两次并丢弃第一个结果。您应该重新组织代码,以便它可以在readObject()中阻塞

    你还有其他问题。您正在为null?测试readObject()的结果,但是如果您在发送方写入了null,它只返回null。我怀疑你把它当作EOS测试,但它是无效的readObject()在EOS上抛出EOFException。您应该重新组织代码,以便它可以在readObject()中阻塞