Java序列化与反序列化

         Java 提供了对象序列化的机制,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。

将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。

类ObjectInputStream 和ObjectOutputStream是高层次的数据流,它们包含序列化和反序列化对象的方法。

序列化方法:

public final void writeObject(Object x) throws IOException

反序列化方法:

public final Object readObject() throws IOException, ClassNotFoundException
直接上代码:
/**
*类必须实现Serializable接口才能序列化
*/
public class User implements Serializable{
     private String name;
     private String address;
     private int age;
     private transient int num;
     //提供get和set方法
}
/**
*序列化:   当序列化一个对象到文件时, 按照Java的标准约定是给文件一个.ser扩展名。
*/
public class SerializeDemo {
     public static void main(String[] args) throws IOException {
  	User user = new User();
  	user.setName("zy");
  	user.setAddress("zhonghe");
  	user.setAge(24);
  	user.setNum(2323);
  	FileOutputStream file = new FileOutputStream("D://user.ser");
  	ObjectOutputStream out = new ObjectOutputStream(file);
  	out.writeObject(user);
  	out.close();
  	file.close();
     }
}

/**

*反序列化 :反序列化在DeSerializeDemo程序中创建User对象。

*当对象被序列化时,属性num的值为2323,但是因为该属性是短暂的,该值没有被发送到输出流。所以反序列化后User对象的sum属性为0。

*/

public class DeSerializeDemo {
         public static void main(String[] args) throws IOException, ClassNotFoundException {
                FileInputStream fileInput = new FileInputStream("D://user.ser");
               ObjectInputStream in = new ObjectInputStream(fileInput);
               User user = (User) in.readObject();
               in.close();

               fileInput.close();
              System.out.println(user.getName());
              System.out.println(user.getAddress());
              System.out.println(user.getAge());
              System.out.println(user.getNum());
       }
}

输出:zy
            zhonghe
            24
            0

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值