简体   繁体   中英

Object Serialization in Java Behaviour of readObject()

Let's say I have a Person class and I am using ObjectInputStream and ObjectOutputStream with a FileInputStream and FileOutputStream to read and write the object to a file. If i have various objects of class Person, for example person1 , person2 , person3 and i use

writeObject(person1)
writeObject(person2)
writeObject(person3)

When I do

Person p1 = (Person) in.readObject()

will p1 be equal to person1 or person3 ? In other words, does readObject follow a stack or queue sort of behaviour. Does it read the objects in the order they were written or does it read them in the reverse order?

will p1 be equal to person1 or person3? In other words, does readObject follow a stack or queue sort of behaviour. Does it read the objects in the order they were written or does it read them in the reverse order?

readObject() method read an object from the ObjectInputStream in the same order in which they are written to the stream. So in your case p1 will be equal to person1. Here is an example

import java.io.*;


public class Example {

   static class Person implements Serializable {
      String name;

      public Person(String name) {
         this.name = name;
      }

      @Override
      public String toString() {
         return "Person{" +
                 "name='" + name + '\'' +
                 '}';
      }
   }
   public static void main(String[] args) {

      Person person1 = new Person("Adam");
      Person person2 = new Person("John");
      try {

         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         oout.writeObject(person1);
         oout.writeObject(person2);
         oout.flush();

         ObjectInputStream ois =
                 new ObjectInputStream(new FileInputStream("test.txt"));

         System.out.println("" +  ois.readObject());
         System.out.println("" +  ois.readObject());


      } catch (Exception ex) {
         ex.printStackTrace();
      }

   }
}

It outputs

Person{name='Adam'}
Person{name='John'}

The same order in which objects were written via

oout.writeObject(person1);
 oout.writeObject(person2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM