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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM