• 热门专题

java的Serializable功能

作者:  发布日期:2014-03-07 22:18:56
  • 可以将java对象序列化为文件,也可以将文件反序列化为java对象

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

    DeserializeFile2Object.java

     

    package com.zuidaima.util;
    
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    
    /**
     * 反序列化文件到java对象
     * 
     * @author javaniu
     * 
     */
    public class DeserializeFile2Object {
    
    	public static void main(String[] args) {
    		Address address = deserialzeAddress();
    		System.out.println(address);
    	}
    
    	public static Address deserialzeAddress() {
    
    		Address address;
    
    		try {
    
    			FileInputStream fin = new FileInputStream("c:/address.ser");
    			ObjectInputStream ois = new ObjectInputStream(fin);
    			address = (Address) ois.readObject();
    			ois.close();
    
    			return address;
    
    		} catch (Exception ex) {
    			ex.printStackTrace();
    			return null;
    		}
    	}
    
    }
    
    	    			

     

    SerializeObject2File.java

     

    package com.zuidaima.util;
    
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    
    /**
     * 序列化java对象到文件
     * 
     * @author javaniu
     * 
     */
    public class SerializeObject2File {
    
    	public static void main(String args[]) {
    		serializeAddress("北京朝阳区", "中国");
    	}
    
    	public static void serializeAddress(String street, String country) {
    
    		Address address = new Address();
    		address.setStreet(street);
    		address.setCountry(country);
    
    		try {
    
    			FileOutputStream fout = new FileOutputStream("c:\address.ser");
    			ObjectOutputStream oos = new ObjectOutputStream(fout);
    			oos.writeObject(address);
    			oos.close();
    			System.out.println("Done");
    
    		} catch (Exception ex) {
    			ex.printStackTrace();
    		}
    	}
    
    }
    
    	    			

    代码下载地址:http://www.zuidaima.com/share/1550463266802688.htm

     

延伸阅读:

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规