java 序列化和反序列化多个对象

 1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.OutputStream;
5 import java.io.InputStream;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8 import java.io.Serializable;
9 class Person implements Serializable{
10 private transient String name;//设置transient,name不会被序列化
11 private int age;
12 public Person(String name,int age){
13 this.name=name;
14 this.age=age;
15 }
16 public String toString(){
17 return "姓名:"+this.name+";姓名:"+this.age;
18 }
19 }
20 public class CharSetDemo {
21 public static void main(String[] args) throws Exception {
22 Person per[]={
23 new Person("张三",30),new Person("李四",31),new Person("王五",32)
24 };
25 ser(per);
26 Object o[]=dser();
27 for(int i=0;i<o.length;i++){
28 Person p=(Person) o[i];
29 System.out.println(p);
30 }
31 }
32 public static void ser(Object obj[]) throws Exception{
33 File f=new File("d:"+File.separator+"test.txt");
34 OutputStream out=new FileOutputStream(f);
35 ObjectOutputStream oos=null;
36 oos=new ObjectOutputStream(out);
37 oos.writeObject(obj);
38 oos.close();
39 }
40 public static Object[] dser() throws Exception{
41 File f=new File("d:"+File.separator+"test.txt");
42 ObjectInputStream ois=null;
43 InputStream ipt=new FileInputStream(f);
44 ois=new ObjectInputStream(ipt);
45 Object obj[]=(Object []) ois.readObject();
46 ois.close();
47 return obj;
48 }
49 }
原文地址:https://www.cnblogs.com/dennisac/p/2418500.html