标签:
对象的序列化是指将对象转换为字节序列的过程
对象的反序列化是指将字节序列恢复对象的过程
主要有两种用途:
1、把对象的字节序列永久地保存在硬盘上,通常放在一个文件中。
2、在网络上传输对象的字节序列。
Person类
package com.zyz; import java.io.Serializable; /** * Created by Administrator on 16-9-25. */ public class Person implements Serializable { private String name; private int age; private String sex; 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
测试类
package com.zyz; import java.io.*; import java.text.MessageFormat; /** * Created by Administrator on 16-9-25. */ public class TestObjSerializeAndDeserialize { public static void main(String[] args){ // try { // SerializePerson(); // } catch (IOException e) { // e.printStackTrace(); // } try {
SerializePerson(); Person person=DeserializPerson(); System.out.println(MessageFormat.format("姓名:{0},年龄:{1},性别:{2}",person.getName(),person.getAge(),person.getSex())); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static void SerializePerson() throws IOException { Person person=new Person(); person.setName("乔大爷"); person.setAge(40); person.setSex("男"); ObjectOutputStream oo=new ObjectOutputStream(new FileOutputStream(new File("d:/person.txt"))); oo.writeObject(person); System.out.println("文件序列化成功!"); oo.close(); } private static Person DeserializPerson() throws IOException, ClassNotFoundException { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("d:/person.txt"))); Person person=(Person)ois.readObject(); System.out.println("Person对象反序列化成功!"); return person; } }
标签:
原文地址:http://www.cnblogs.com/beast-king/p/5906046.html