<script>function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>
对象串行化,有这样一个说法:
对象的寿命通常随着生成该对象的程序的终止而终止。有时候,可能需要将对象的状态保存下来,在需要时再将对象恢复。我们把对象的这种能记录自己的状态以便将来再生的能力,叫做对象的持续性(persistence)。对象通过写出描述自己状态的数值来记录自己,这个过程叫对象的串行化(Serialization)。
在java.io包中,接口serialization用来作为实现对象串行化的工具 ,只有实现了serialization的类的对象才可以被串行化。
下面的例子给出了保存一个对象的方法:
- List list = ......
- try{
- ObjectOutputStreamout=newObjectOutputStream(
- newFileOutputStream("data_save.dat"));
- out.writeObject(list);
- out.close();
- }catch(FileNotFoundExceptione1){
- e1.printStackTrace();
- }catch(IOExceptione1){
- e1.printStackTrace();
- }
通过ObjectOutputStream对象,保存串行对象。通过FileOutputStream对象把串行对象保存到文件data_save.dat中。
- try{
- ObjectInputStreamin=newObjectInputStream(
- newFileInputStream("data_save.dat"));
- Listlist2=(ArrayList)in.readObject();
- Map<String,Object>map2=null;
- for(inti=0;i<list.size();i++){
- map=list.get(i);
- System.out.println(map);
- }
- }catch(FileNotFoundExceptione1){
- e1.printStackTrace();
- }catch(IOExceptione1){
- e1.printStackTrace();
- }catch(ClassNotFoundExceptione){
- e.printStackTrace();
- }
通过ObjectInputStream对象获取串行对象,通过FileInputStream对象读取保存的数据。