/* 序列化与反序列化 注意:对象的序列化与反序列化使用的类要严格一致,包名,类名,类结构等等所有都要一致。 */ public class Test1 { public static void main(String[] args) { try { // Test1.testSerialize(); Test1.testD(); } catch (Exception e) { e.printStackTrace(); } } //对象的序列化 public static void testSerialize() throws Exception{ //定义对象的输出流,把对象的序列化之后的流放到指定的文件中 ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream("C:\\Users\\李浩\\Desktop\\1\\src\\date8_23\\tt1.txt")); Person p= new Person(); p.name="张三"; p.age= 10; out.writeObject(p); out.flush();//刷写数据到硬盘 out.close(); } public static void testD() throws Exception{ //创建对象输入流对象,从指定的文件中把对象序列化后的流读取出来 ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\李浩\\Desktop\\1\\src\\date8_23\\tt1.txt")); Object obj=in.readObject(); Person p = (Person) obj; System.out.println(p.name); System.out.println(p.age); in.close(); } }
Person.java
public class Person implements Serializable { /* 一个表示序列化的版本标识符的静态变量 用来表明类的不同版本间的兼容性 */ private static final long seiaVersionUID = 1L; String name ; int age; }