标签:dem ack person vat tin get 不能 文件中 add
序列化:将对相中的数据写入到文件。
反序列化:将对象的数据从文件中读取出来。
要实现序列化或反序列化必须实现接口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; } }
标签:dem ack person vat tin get 不能 文件中 add
原文地址:https://www.cnblogs.com/zhai1997/p/11367955.html