package day19_FileOperation; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /* * 定义一个可以被序列化的类 * 此时Person类产生的每一个对象都可以实现二进制的数据传输,属于可以被序列化的程序类 *实现序列化与反序列化 */ class Person implements Serializable { //Person可以被序列化 private static final long serialVersionUID = 1L ; private transient String name ; //在进行序列化处理的时候name属性的内容不会被保存下来(读取的时候读取默认值,即"") private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } @Override public String toString() { return "姓名:"+this.name +"年龄为:"+this.age ; } } public class java_Serializable { private static final File SAVE_FILE = new File ("G:"+File.separator+"java"+File.separator+"tao.txt"); public static void main(String[] args) throws Exception{ saveObject(new Person ("小花",34)); System.out.println(loadObject()); } public static void saveObject(Object obj) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_FILE)) ; oos.writeObject(obj); //输出对象,序列化 oos.close(); //关闭资源 } public static Object loadObject () throws Exception{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SAVE_FILE)) ; Object obj = ois.readObject() ; //反序列化 ois.close(); return obj ; } }
序列化案例
最新推荐文章于 2021-08-09 23:52:45 发布