Java中的序列化问题

       Java序列化是指将Java中的类对象状态以字节的形式保存,需要的时候可以解码获取,通常用于共享数据交互、网络通信等。在Java中,属于对象的状态才应该保存,因此,静态数据成员不能保存;如果不愿意保存某个变量,可以将此变量声明为transient;另外,并不是所有的对象都可以序列化,系统级的类对象如Thread、OutputStream、Socket等类及其子类对象是不可以序列化的。

       要序列化某个对象,只需要类实现java.io.Serializable接口。如下例子:

 1 package de.vogella.java.serilization;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Person implements Serializable {
 6   private String firstName;
 7   private String lastName;
 8   // stupid example for transient
 9   transient private Thread myThread;
10 
11   public Person(String firstName, String lastName) {
12     this.firstName = firstName;
13     this.lastName = lastName;
14     this.myThread = new Thread();
15   }
16 
17   public String getFirstName() {
18     return firstName;
19   }
20 
21   public void setFirstName(String firstName) {
22     this.firstName = firstName;
23   }
24 
25   public String getLastName() {
26     return lastName;
27   }
28 
29   public void setLastName(String lastName) {
30     this.lastName = lastName;
31   }
32 
33   @Override
34   public String toString() {
35     return "Person [firstName=" + firstName + ", lastName=" + lastName
36         + "]";
37   }
38 
39 } 
 1 package de.vogella.java.serilization;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.ObjectInputStream;
 6 import java.io.ObjectOutputStream;
 7 
 8 public class Main {
 9   public static void main(String[] args) {
10     String filename = "time.ser";
11     Person p = new Person("Lars", "Vogel");
12 
13     // Save the object to file
14     FileOutputStream fos = null;
15     ObjectOutputStream out = null;
16     try {                                                     // 编码(序列化)的一般形式 
17       fos = new FileOutputStream(filename); //定义保存的文件对象
18       out = new ObjectOutputStream(fos);   //定义对象输出流对象
19       out.writeObject(p);
20 
21       out.close();
22     } catch (Exception ex) {
23       ex.printStackTrace();
24     }
25     // Read the object from file
26     // Save the object to file
27     FileInputStream fis = null;
28     ObjectInputStream in = null;
29     try {
30       fis = new FileInputStream(filename);  // 解码(反序列化)的一般形式
31       in = new ObjectInputStream(fis);
32       p = (Person) in.readObject();
33       out.close();
34     } catch (Exception ex) {
35       ex.printStackTrace();
36     }
37     System.out.println(p);
38   }
39 } 

 

转载于:https://www.cnblogs.com/YukiJohnson/archive/2012/12/11/2813697.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值