JAVA 序列化_基础

JAVA序列化

  实现 Serializable 接口的对象,可以序列化为本地文件

简单示例:

1 //序列化类
2 public class Test implements Serializable {
3     private String name;  
4     public Test(String name)  {  
5       this.name = name;     
6     }
7 }    

 

 1 public class UseTest
 2 {
 3  public static void main(String[] args)  
 4  {
 5    String path = "D:\\Zhong\\Test\\tes.txt"; 
 6    Test test1 = new Test("Mr.Zhong");  
 7    File file = new File(path); 
 8    try  
 9   {  
10    file.createNewFile();  
11   }  
12   catch(IOException e)  
13   {  
14    e.printStackTrace();  
15   }  
16   try  
17   {  
18     //序列化
19     FileOutputStream fos = new FileOutputStream(file);
20     ObjectOutputStream oos = new ObjectOutputStream(fos);
21     oos.write(test1);
22     oos.flush();  
23     oos.close();  
24     fos.close();  
25 
26      //反序列化
27     FileInputStream fis = new FileInputStream(file);  
28     ObjectInputStream ois = new ObjectInputStream(fis); 
29     Test test2 = (Test)ois.readObject();
30     ois.close();  
31     fis.close(); 
32    } catch(ClassNotFoundException e)  
33   {  
34    e.printStackTrace();  
35   }  
36   catch (IOException e)  
37   {  
38    e.printStackTrace();  
39   }               
40  }
41 }            

 

posted @ 2017-02-27 17:30  Mr.Zhongzz  阅读(127)  评论(0)    收藏  举报