序列化: 将对相中的数据写入到文件.
反序列化: 将对象的数据从文件中读取出来.
要实现序列化或反序列化必须实现接口 Serializable .
1, 序列化
- package pers.zxc.xulie;
- import java.io.Serializable;
- public class Person implements Serializable{
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
- package pers.zxc.xulie;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectOutputStream;
- public class Test {
- public static void main(String[] args) throws IOException {
- FileOutputStream fos = new FileOutputStream("E:\\IO 流 \\java\\2221.txt");
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(new Person("Tom", 12));
- oos.close();
- }
- }
运行结果不能看懂, 但是可以通过反序列化将数据读出来.
2, 反序列化
- package pers.zxc.xulie;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- public class ReadDemo {
- public static void main(String[] args) throws IOException,
- ClassNotFoundException {
- FileInputStream fis = new FileInputStream("E:\\IO 流 \\java\\2221.txt");
- ObjectInputStream ois = new ObjectInputStream(fis);
- Person obj = (Person) ois.readObject();
- System.out.println(obj.toString());
- }
- }
将序列化的结果读了出来.
3, 瞬态关键字 transient
被 transient 关键字修饰后, 属性就不会被序列化. 同时, 被静态修饰符修饰后的属性也不会被序列化.
- package pers.zxc.xulie;
- import java.io.Serializable;
- public class Person implements Serializable{
- private String name;
- private transient int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
来源: http://www.bubuko.com/infodetail-3159204.html