Java序列化和反序列化

高洛峰
高洛峰 原创
2016-11-16 11:59:14 1358浏览

Java对序列化提供了非常方便的支持,在定义类的时候,如果想让对象可以被序列化,必须实现 implements Serializable

比如,对已存在的wang.txt进行序列化,得到的字节输出到wang1.txt文件中

package Serializable;
/*
 * 文本文件的序列化
 */
import java.io.*;
 
public class test  implements Serializable
{  
 public static void main(String[] args) throws ClassNotFoundException  
 {  
     File file=new File("D:\\wang.txt");
     File fi = new File("D:\\wang1.txt");  
  try  
  {  
   file.createNewFile();  
  }  
  catch(IOException e)  
  {  
   e.printStackTrace();  
  }  
  try  
  {  
   //序列化
   FileOutputStream fos = new FileOutputStream(fi);  
   ObjectOutputStream oos = new ObjectOutputStream(fos);  
   oos.writeObject(file);  
   oos.flush();  
   oos.close();  
   fos.close();  
    
   //反序列化
   FileInputStream fis = new FileInputStream(fi);  
   ObjectInputStream ois = new ObjectInputStream(fis);  
   File file1= (File) ois.readObject();    //反序列化一个对象
  }  
  catch (IOException e)  
  {  
   e.printStackTrace();  
  }               
 }  
}


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。