★ 序列化(把对象写入文件必须实现序列化)
将一个对象存放到某种类型的永久存储器上称为保持。如果一个对象可以被存放到磁盘或磁带上,或者可以发送到另外一台机器并存放到存储器或磁盘上,那么这个对象就被称为可保持的。(在Java中,序列化、持久化、串行化是一个概念。)
java.io.Serializable接口没有任何方法,它只作为一个“标记者”,用来表明实现了这个接口的类可以考虑串行化。类中没有实现Serializable的对象不能保存或恢复它们的状态。
★ 对象图
当一个对象被串行化时,只有对象的数据被保存;方法和构造函数不属于串行化流。如果一个数据变量是一个对象,那么这个对象的数据成员也会被串行化。树或者对象数据的结构,包括这些子对象,构成了对象图。
★ 瞬时 transient
防止对象的属性被序列化。
import java.io.Serializable;
public class Person implements Serializable {//相当于贴标签,Person对象可以被写入永久存储器(文件)中
private static final long serialVersionUID = 1L;
private String name;
private int num;
private int age;
// private transient int age;//transient瞬时变量,不会序列化--不能被永久保存
private static int sum=0;//静态无法序列化
private MyDate m=null;
public Person() {
num=++sum;
}
public Person(String name, int age,MyDate m) {//串行化MyDate,MyDate必须要实现序列化
this();
this.name = name;
this.age = age;
this.m=m;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return num+ ":" + name + "," + age+","+m;
}
}
import java.io.Serializable;
public class MyDate implements Serializable{
private static final long serialVersionUID = 1L;
private int year,month,day;
public MyDate(int year, int month, int day) {
super();
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString() {
return year + "年," + month + "月," + day+ "日";
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Demo {
public static void main(String[] args) throws Exception{
writeDemo();
readDemo();
}
public static void readDemo() throws IOException,FileNotFoundException{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("files/objs.txt"));
while (true) {//读到文件结尾出异常
try {
Person p = (Person) in.readObject();
System.out.println(p);
} catch (Exception e) {//对象流的读取,应该用处理异常的方式来判断文件结束
System.out.println("file read all...");
break;
}
// finally{
// break;//只会对一个对象
// }
}
}
public static void writeDemo() throws IOException,FileNotFoundException{
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("files/objs.txt"));
out.writeObject(new Person("jack",24,new MyDate(1995,5,5)));
out.writeObject(new Person("rose",22,new MyDate(1995,5,5)));
out.writeObject(new Person("tom",25,new MyDate(1995,5,5)));
out.writeObject(new Person("luffer",29,new MyDate(1995,5,5)));
}
}