readObject()的Java行为中的对象序列化
假设我有一个Person类,我使用readObject()的Java行为中的对象序列化,java,object,serialization,Java,Object,Serialization,假设我有一个Person类,我使用ObjectInputStream和ObjectOutputStream和FileInputStream读取对象并将其写入文件。 如果我有Person类的各种对象,例如person1、person2、person3 我用 writeObject(person1) writeObject(person2) writeObject(person3) 当我这样做的时候 Person p1 = (Person) in.readObject() p1将等于person
ObjectInputStream
和ObjectOutputStream
和FileInputStream
读取对象并将其写入文件。
如果我有Person类的各种对象,例如person1、person2、person3
我用
writeObject(person1)
writeObject(person2)
writeObject(person3)
当我这样做的时候
Person p1 = (Person) in.readObject()
p1将等于person1还是person3?换句话说,readObject
是否遵循堆栈或队列类型的行为。它是按写入对象的顺序读取对象,还是按相反的顺序读取对象
p1将等于person1还是person3?换言之,它确实如此
readObject遵循堆栈或队列类型的行为。它读了吗
对象的写入顺序,还是在
倒序
readObject()
方法从ObjectInputStream中以写入流的相同顺序读取对象。因此,在您的情况下,p1
将等于person1。这里有一个例子
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();
}
}
}
它输出
Person{name='Adam'}
Person{name='John'}
与通过写入对象的顺序相同
oout.writeObject(person1);
oout.writeObject(person2);
你可以很容易地测试这一点,并得到你的答案。但为了缩短时间:它将按照对象的写入顺序读取对象