java序列化与反序列化操作实例分析
本文实例分析了java序列化与反序列化操作。分享给大家供大家参考,具体如下:
概述:
Java序列化是指把Java对象转换为字节序列的过程;而Java反序列化是指把字节序列恢复为Java对象的过程。
示例代码:
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.io.Serializable;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.List;
publicclassTest{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
try{
ObjectOutputStreamout=newObjectOutputStream(newFileOutputStream("D:/objectFile.obj"));
Customercustomer=newCustomer("中国人",23);
out.writeObject("你好!");
out.writeObject(newDate());
out.writeObject(customer);
out.writeInt(123);
Listlist=newArrayList();
inti=0;
while(i<100){
Customercustomer2=newCustomer("中国人",i);
list.add(customer2);
i++;
}
HashMaphashMap=newHashMap();
hashMap.put("customer",list);
out.writeObject(hashMap);
out.close();
ObjectInputStreamin=newObjectInputStream(newFileInputStream("D:/objectFile.obj"));
System.out.println("obj1="+(String)in.readObject());
System.out.println("obj2="+(Date)in.readObject());
Customerobj3=(Customer)in.readObject();
System.out.println("obj3="+obj3);
intobj4=in.readInt();
System.out.println("obj4="+obj4);
Objectobj5=in.readObject();
System.out.println(obj5);
HashMaphash_map=(HashMap)obj5;
Listl=(List)hash_map.get("customer");
System.out.println("size:"+l.size());
for(intii=0;ii<l.size()-1;ii++){
Customerc=(Customer)l.get(ii);
System.out.println(c.getName());
System.out.println(c.getAge());
}
in.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
}
}
classCustomerimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateStringname;
privateintage;
publicStringgetName(){
returnname;
}
publicintgetAge(){
returnage;
}
publicCustomer(Stringname,intage){
this.name=name;
this.age=age;
}
publicStringtoString(){
return"name="+name+",age="+age;
}
}
希望本文所述对大家java程序设计有所帮助。