Java Serializable不会读取正确的对象

时间:2015-05-18 16:21:52

标签: java arrays

我想将一个对象转换为一个字节数组,并将该数组转换回一个对象。一切正常,除了将数组转换回对象的方法不会打印出正确的对象。

public static List<Person> list_interviewees;
    main { 
        list_interviewees = new ArrayList<Person>();
        Person p = new Person();
        p.setAge(20);
        p.setDegree("bhd");
        p.setLastJob("asd");
        p.setLastName("Test");
        p.setName("Tester");
        list_interviewees.add(p);
        Person p2 = new Person();
        p2.setAge(20);
        p2.setDegree("bhd");
        p2.setLastJob("asd");
        p2.setLastName("QWEQW");
        p2.setName("ASAD");
        list_interviewees.add(p2);
        transferBytes();
        }

    public static void sendBytes(byte[] b) {
        System.out
                .println("++++++ This method simulates sending information to other site and reads the data");
        System.out.println("Received bytes" + b);
        System.out.println("Total bytes" + b.length);

        Person p = null;

        try (ByteArrayInputStream bis = new ByteArrayInputStream(b);
                ObjectInputStream in = new ObjectInputStream(bis);) {
            p = (Person) in.readObject();
            System.out.println(p.getName() + " " + p.getLastName());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static void transferBytes() {

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bos);) {

            for (Person p : list_interviewees) {

                out.writeObject(p);
                sendBytes(bos.toByteArray());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

如果我运行上面的代码,我得到输出

  

++++++此方法模拟将信息发送到其他站点并读取数据

     

收到的字节数[B @ 4aa298b7

     

总字节数158

     

测试人员测试

     

++++++此方法模拟将信息发送到其他站点并读取数据

     

收到的字节数[B @ 4554617c

     

总字节数195

     

测试人员测试

为什么我在那里得到两次Tester测试名称? 我检查了通过调试器发送的人,它是正确的,所以为什么sendBytes方法收到错误的数组?

0 个答案:

没有答案