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

java学习IO流之对象序列化

2015-03-10 10:21 232 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: