Serializable:
概念:对象的序列化,就是将一个实现了Serializable接口的对象转换成一组byte数组。
实现:实现Serializable接口
作用:对象的持久化;跨平台;跨网络;支持RMI调用
实例:
import java.io.Serializable;
//可序列化对象
public class Student implements Serializable{
int id;//学号
int age;//年龄
String name;//姓名
<span style="color:#ff0000;">transient</span> String sex;//性别
public Student(int id, int age, String name, String sex) {
super();
this.id = id;
this.age = age;
this.name = name;
this.sex = sex;
}
}
public class SaveStudent {
public static void main(String args[]) throws Exception{
//创建对象
Student student = new Student(1, 10, "张三", "male");
//对象输出
//输出流
FileOutputStream fos = new FileOutputStream("D:\\桌面\\a.txt");
//对象输出流
ObjectOutputStream os = new ObjectOutputStream(fos);
//写出对象
os.writeObject(student);
//输出流
os.close();
fos.close();
student = null;
//对象输入
//输入流
FileInputStream fis = new FileInputStream("D:\\桌面\\a.txt");
//对象输入流
ObjectInputStream oi = new ObjectInputStream(fis);
//读取对象
student = (Student) oi.readObject();
System.out.println("age="+student.age+" id="+student.id+" name="+student.name+" sex="+student.sex);
}
}
注意:
1、串行化内容:能保存非静态变量,不能保存任何的方法和静态内容,不保存任何的权限例如private内容
2、可以在变量前使用关键字transient来取消该字段的序列化