【java】对象序列化Serializable、transient

 1 package 对象序列化;
 2 
 3 import java.io.Serializable;
 4 
 5 @SuppressWarnings("serial")
 6 class A implements Serializable{
 7     
 8 }
 9 public class TestSerializable {
10     public static void main(String[] args) {
11         
12     }
13 }
View Code

 对象序列化:java.io.ObjectOutputStream

对象反序列化:java.io.ObjectInputStream

 1 package 对象序列化;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.io.ObjectInputStream;
 9 import java.io.ObjectOutputStream;
10 import java.io.Serializable;
11 
12 @SuppressWarnings("serial")
13 class A implements Serializable{
14     private String name;
15     private transient int age;//transient修饰的成员不能被序列化
16     public A(String name,int age){
17         this.name=name;
18         this.age=age;
19     }
20     @Override
21     public String toString() {
22         return "name="+name+",age="+age;
23     }
24 }
25 public class TestSerializable {
26     public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
27         ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("D:"+File.separator+"A.ser")));
28         oos.writeObject(new A("张三",23));
29         oos.close();
30         
31         ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("D:"+File.separator+"A.ser")));
32         A a=(A)ois.readObject();
33         ois.close();
34         System.out.println(a);
35     }
36 }
Serializable和transient应用示例

 

posted @ 2017-04-09 19:10  xiongjiawei  阅读(406)  评论(0编辑  收藏  举报