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 }            

 

转载于:https://www.cnblogs.com/Zhongzz/p/6475455.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值