JAVA中的Serializable对象序列化
一个十分简单的小例子,希望能给你带来帮助。
重点:
1、实现Serializale接口。
2、实现对应的序列化和反序列化函数。
3、要理解什么时候用对象序列化。
import java.io.*;
class Communicate implements Serializable //要实现Serializable接口
{
private String name;
private String tel;
private String phone;
private String addr;
private String email;
public Communicate()
{
}
public Communicate(String name,String tel,String phone,String addr,String email)
{
this.name=name;
this.tel=tel;
this.phone=phone;
this.addr=addr;
this.email=email;
}
public void writeObject(java.io.ObjectOutputStream out)throws IOException//实现序列化函数
{
out.writeObject(this);
}
public Communicate readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException//实现反序列化函数
{
return (Communicate)in.readObject();
}
public String toString()
{
return "name : "+name+"\ttel :"+tel+"\tphone :"+phone+"\taddr :"+addr+"\temail :"+email;
}
}
class Test
{
public static void main(String []args)
{
try
{
FileOutputStream fos=new FileOutputStream("A.txt");
FileInputStream fis=new FileInputStream("A.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
ObjectInputStream ois=new ObjectInputStream(fis);
Communicate com=new Communicate("张三","123566333","545465654","山东","zs@126.com");
com.writeObject(oos);
oos.close();
fos.close();
Communicate com1=new Communicate();
com1=com1.readObject(ois);
ois.close();
fis.close();
System.out.println(com);
}
catch (Exception e)
{
System.out.println(e);
}
}
}