您的位置:首页 > 编程语言 > Java开发

java的Serializable功能

2016-07-20 15:20 573 查看

可以将java对象序列化为文件,也可以将文件反序列化为java对象

原创不易,转载请注明出处:分享java的Serializable功能

DeserializeFile2Object.java

 

[java] view plain copy    print?
  1. package com.zuidaima.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.ObjectInputStream;  
  5.   
  6. /** 
  7.  * 反序列化文件到java对象 
  8.  *  
  9.  * @author javaniu 
  10.  *  
  11.  */  
  12. public class DeserializeFile2Object {  
  13.   
  14.     public static void main(String[] args) {  
  15.         Address address = deserialzeAddress();  
  16.         System.out.println(address);  
  17.     }  
  18.   
  19.     public static Address deserialzeAddress() {  
  20.   
  21.         Address address;  
  22.   
  23.         try {  
  24.   
  25.             FileInputStream fin = new FileInputStream("c:/address.ser");  
  26.             ObjectInputStream ois = new ObjectInputStream(fin);  
  27.             address = (Address) ois.readObject();  
  28.             ois.close();  
  29.   
  30.             return address;  
  31.   
  32.         } catch (Exception ex) {  
  33.             ex.printStackTrace();  
  34.             return null;  
  35.         }  
  36.     }  
  37.   
  38. }  
  39.   
  40.                       

 

 

SerializeObject2File.java

 

[java] view plain copy    print?
  1. package com.zuidaima.util;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.ObjectOutputStream;  
  5.   
  6. /** 
  7.  * 序列化java对象到文件 
  8.  *  
  9. 1bb8b  * @author javaniu 
  10.  *  
  11.  */  
  12. public class SerializeObject2File {  
  13.   
  14.     public static void main(String args[]) {  
  15.         serializeAddress("北京朝阳区", "中国");  
  16.     }  
  17.   
  18.     public static void serializeAddress(String street, String country) {  
  19.   
  20.         Address address = new Address();  
  21.         address.setStreet(street);  
  22.         address.setCountry(country);  
  23.   
  24.         try {  
  25.   
  26.             FileOutputStream fout = new FileOutputStream("c:\\address.ser");  
  27.             ObjectOutputStream oos = new ObjectOutputStream(fout);  
  28.             oos.writeObject(address);  
  29.             oos.close();  
  30.             System.out.println("Done");  
  31.   
  32.         } catch (Exception ex) {  
  33.             ex.printStackTrace();  
  34.         }  
  35.     }  
  36.   
  37. }  
  38.   
  39.                       
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: