java学习IO流之对象序列化

package learn;
import java.io.*;
public class learnTen {

	/**
	 * 序列化对象
	 * @param args
	 */
	public static void serialise(Emplo e){
		
		try
	      {
	         FileOutputStream fileOut =
	         new FileOutputStream("D:/java/employee.ser");
	         ObjectOutputStream out = new ObjectOutputStream(fileOut);
	         
	         out.writeObject(e);
	         out.close();
	         fileOut.close();
	         System.out.printf("Serialized data is saved in D:/java/employee.ser");
	      }catch(IOException i)
	      {
	          i.printStackTrace();
	      }
	}
	
	
	/**
	 * 
	 * @param args
	 * 读取序列化对象信息
	 */
	
	public static void unserialise(){
		Emplo f =null;
		try{
			
			 FileInputStream fn = new FileInputStream("D:/java/employee.ser");
	         ObjectInputStream in = new ObjectInputStream(fn);
			 f = (Emplo) in.readObject();
				
		}catch(IOException o){
			o.printStackTrace();
		}catch(ClassNotFoundException c)
	      {
	         System.out.println("Emplo class not found");
	         c.printStackTrace();
	         return;
	      }
		
		 System.out.println("\nUnserialized Employee...");
	     System.out.println("Name: " + f.name);
	     System.out.println("Address: " + f.address);
	     System.out.println("Phone: " + f.phone);
	     f.say();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Emplo e = new Emplo("王勇","四川广安",1597412);
		learnTen.serialise(e);
		learnTen.unserialise();
		
	}

}


/**
 * 
 * @author Administrator
 *用于序列化的对象一定要实现java.io。Serializable
 */
 class Emplo implements java.io.Serializable{
	public String name;
	public String address;
	public int phone;
	
	 Emplo(String name,String address,int phone){
		this.name=name;
		this.address=address;
		this.phone=phone;
	}
	 
	 public void say(){
		 System.out.print("序列化一个对象:"+name+":"+address+":"+phone);
	 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值