java:序列化Serializable 接口
public class SerializePerson implements Serializable { private String name; private int age; public SerializePerson(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "姓名:" + name + ", 年龄:" + age; } }
一,单对象序列化
public static void main(String[] args) throws Exception, Exception { // TODO 自动生成的方法存根 if( args[0].equals("set") ) { setPseron(); }else if( args[0].equals("get") ) { getPseron(); }else{ System.out.println("抱歉,你什么都没有输入"); } System.out.println(args[0]); } public static void setPseron() throws Exception, IOException { File file = new File("F:"+File.separator+"work"+File.separator+"work"+File.separator+"a.txt"); ObjectOutputStream oobs = null; oobs = new ObjectOutputStream( new FileOutputStream(file) ); oobs.writeObject(new SerializePerson("张三",22)); oobs.close(); } public static void getPseron() throws Exception, IOException { File file = new File("F:"+File.separator+"work"+File.separator+"work"+File.separator+"a.txt"); ObjectInputStream oips = null; oips = new ObjectInputStream( new FileInputStream(file) ); Object obj = oips.readObject(); SerializePerson per = (SerializePerson) obj; System.out.println(per); }
二。多对象,多数组序列化
public static void main(String[] args) throws Exception, Exception { if(args[0].equals("set")) { setPerson(); }else if(args[0].equals("get")) { Object obj = getPerson(); SerializePerson per[] = (SerializePerson[]) obj; print(per); }else{ System.out.println("请输入一个操作"); } } public static void setPerson() throws Exception, IOException { File file = new File("F:"+File.separator+"work"+File.separator+"work"+File.separator+"person.per"); ObjectOutputStream oopt = new ObjectOutputStream( new FileOutputStream(file) ); SerializePerson per[] = {new SerializePerson("张三",22), new SerializePerson("李四",44), new SerializePerson("王五",33)}; oopt.writeObject(per); oopt.close(); } public static Object getPerson() throws Exception, IOException { File file = new File("F:"+File.separator+"work"+File.separator+"work"+File.separator+"person.per"); ObjectInputStream lis = null; lis = new ObjectInputStream( new FileInputStream(file) ); Object obj = null; obj = lis.readObject(); lis.close(); return obj; } public static void print(SerializePerson per[]) { for(SerializePerson p: per) { System.out.println(p); } }