static静态变量和transit修饰的成员变量不会被序列化
写入
public class STest {
/**
* @throws IOException
* @throws FileNotFoundException
*
*/
public static void main(String[] args) throws FileNotFoundException,
IOException {
Person p = new Person("aa", "23", "165");
Person p1 = new Person("bb", "24", "168");
Person p2 = new Person("cc", "25", "169");
Person p3 = new Person("dd", "26", "190");
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("d:/ht.txt"));
out.writeObject(p3);
out.writeObject(p2);
out.writeObject(p1);
out.writeObject(p);
out.close();
}
}
class Person implements Serializable {
private String username;
private String age;
private String height;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public Person(String username, String age, String height) {
super();
this.username = username;
this.age = age;
this.height = height;
}
}
将三个对象保存到文件中,此时打开文件显示(字节流方式存储)的是
�sr �com.mode.demo.mvnmode.Person?r脿+� �L �aget �Ljava/lang/String;L �heightq ~ �L �usernameq ~ �xpt �26t �190t �ddsq ~ t �25t �169t �ccsq ~ t �24t �168t �bbsq ~ t �23t �165t �aa
读取:
public static void main(String[] args) throws Exception {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("d:/ht.txt"));
Person p = (Person) in.readObject();
Person p1 = (Person) in.readObject();
Person p2 = (Person) in.readObject();
Person p3 = (Person) in.readObject();
System.out.println(p.getUsername());
System.out.println(p1.getUsername());
System.out.println(p2.getUsername());
System.out.println(p3.getUsername());
in.close();
}
打印出的结果:
dd
cc
bb
aa