[英]Object Serialization in Java Behaviour of readObject()
假設我有一個Person類,並且正在使用ObjectInputStream
和ObjectOutputStream
以及FileInputStream
和FileOutputStream
來將對象讀取和寫入文件。 如果我有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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.