java I/O (二)——对象序列化

       对象序列化:将实现了Serializable接口的对象转换成一个字节序列,并能够在以后加你过这个字节序列完全恢复为原来的对象。java.io包中提供了相关的类:Serializable、Externalizable、ObjectInputStream、ObjectOutputStream等。其中Serializable接口没有方法和字段,仅用于标识可序列化的语义。

应用场景:

     在很多应用中,需要对某些对象进行序列化,让它们离开内存空间,入住物理硬盘,以便长期保存。比如最常见的是Web服务器中的Session对象,当有 10万用户并发访问,就有可能出现10万个Session对象,内存可能吃不消,于是Web容器就会把一些seesion先序列化到硬盘中,等要用了,再把保存在硬盘中的对象还原到内存中。

  当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个Java对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为Java对象。

1.默认序列化

/*
 *对象默认序列化,不仅保存了对象的全景图,而且能追踪对象内多包涵的所有引用,并保存那些对象 (所有内容)
 *默认序列化直接从存储的二进制为基础恢复,不调用任何构造器
 *序列化的类必须实现Serializable接口
 */
class House implements Serializable{
	
	private int id = new Random(47).nextInt(20);
	private String name = "房子";
	private BedRoom bedRoom = new BedRoom();
	
	public House(){
		System.out.println("House 构造器");
	}
	
	public String toString(){
		return "" + name + ": " + id + " 有" + bedRoom.name + ": " + bedRoom.id;
	}
}

class BedRoom implements Serializable{
	 int id = new Random(47).nextInt(10);
	 String name = "卧室";
	 
	 public BedRoom(){
		 System.out.println("BedRoom构造器");
	 }
}

//在对一个Serializable对象进行还原的过程中,没有调用任何构造器
public class TestSerializable {
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		House house = new House();
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("E:/J2EE/新建文件夹/serializable/house.out"));
		out.writeObject("这是一个String对象");
		out.writeObject(house);
		out.close();
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("E:/J2EE/新建文件夹/serializable/house.out"));
		System.out.println((String)in.readObject());
		System.out.println((House)in.readObject());
		in.close();
	}
}
2.如果我们想控制序列化的过程,(规定序列化哪些内容)可以通过以下两种方法实现:实现Externalizable接口、使用transient关键字

方法一:

/*
 * 序列化一个Externalizable对象会按照writeExternal()方法进行
 * 对于恢复一个Externalizable的对象,所有普通的构造器都会被调用(包括在字段定义时的初始化)
 * 然后调用readExternal()方法
 */
public class LoginInfo implements Externalizable{
	
	private Date date = new Date();
	public String userName;
	public String password;
	
	public LoginInfo(){
		System.out.println("我是普通构造器");
	}
	
	public LoginInfo(String userName, String password){
		this.userName = userName;
		this.password = password;
	}
	
	public String toString(){
		return "" + date  + "  " + userName + "   " + password;
	}
	
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(date);
		out.writeObject(userName);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		date = (Date)in.readObject();
		userName = (String)in.readObject();
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		LoginInfo info = new LoginInfo("liushuo","liushuo");
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("E:/J2EE/新建文件夹/serializable/login.out"));
		out.writeObject(info);
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("E:/J2EE/新建文件夹/serializable/login.out"));
		LoginInfo loginInfo = (LoginInfo)in.readObject();
		System.out.println(loginInfo);
	}
	
}

方法二:

/*
 *使用transient关键字逐个字段的关闭序列化 
 */
public class LoginByTransient implements Serializable{
	private Date date = new Date();
	public String userName;
	public transient String password;
	
	public LoginByTransient(){
		System.out.println("我是普通构造器");
	}
	
	public LoginByTransient(String userName, String password){
		this.userName = userName;
		this.password = password;
	}
	
	public String toString(){
		return "" + date  + "  " + userName + "   " + password;
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		LoginByTransient info = new LoginByTransient("liushuo","liushuo");
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("E:/J2EE/新建文件夹/serializable/loginTran.out"));
		out.writeObject(info);
		out.close();
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("E:/J2EE/新建文件夹/serializable/loginTran.out"));
		LoginByTransient loginInfo = (LoginByTransient)in.readObject();
		in.close();
		System.out.println(loginInfo);
	}

}


3.对于static的字段必须自己手动显示的实现


4.关于serialVersionUID

serialVersionUID的取值是Java运行时环境根据类的内部细节自动生成的。如果对类的源代码作了修改,再重新编译,新生成的类文件的serialVersionUID的取值有可能也会发生变化。
  类的serialVersionUID的默认值完全依赖于Java编译器的实现,对于同一个类,用不同的Java编译器编译,有可能会导致不同的 serialVersionUID,也有可能相同。为了提高serialVersionUID的独立性和确定性,强烈建议在一个可序列化类中显示的定义serialVersionUID,为它赋予明确的值

  显式地定义serialVersionUID有两种用途:
    1、 在某些场合,希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有相同的serialVersionUID;
    2、 在某些场合,不希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有不同的serialVersionUID。

以下内容转载于:http://www.cnblogs.com/xdp-gacl/p/3777987.html

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TestSerialversionUID {

    public static void main(String[] args) throws Exception {
        SerializeCustomer();// 序列化Customer对象
        Customer customer = DeserializeCustomer();// 反序列Customer对象
        System.out.println(customer);
    }

    /**
     * MethodName: SerializeCustomer 
     * Description: 序列化Customer对象
     * @author xudp
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void SerializeCustomer() throws FileNotFoundException,
            IOException {
        Customer customer = new Customer("gacl",25);
        // ObjectOutputStream 对象输出流
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
                new File("E:/Customer.txt")));
        oo.writeObject(customer);
        System.out.println("Customer对象序列化成功!");
        oo.close();
    }

    /**
     * MethodName: DeserializeCustomer 
     * Description: 反序列Customer对象
     * @author xudp
     * @return
     * @throws Exception
     * @throws IOException
     */
    private static Customer DeserializeCustomer() throws Exception, IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                new File("E:/Customer.txt")));
        Customer customer = (Customer) ois.readObject();
        System.out.println("Customer对象反序列化成功!");
        return customer;
    }
}

/**
 * <p>ClassName: Customer<p>
 * <p>Description: Customer实现了Serializable接口,可以被序列化<p>
 * @author xudp
 * @version 1.0 V
 * @createTime 2014-6-9 下午04:20:17
 */
class Customer implements Serializable {
    //Customer类中没有定义serialVersionUID
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /*
     * @MethodName toString
     * @Description 重写Object类的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}
序列化与反序列化运行成功

下面我们修改一下Customer类,添加多一个sex属性,如下:

class Customer implements Serializable {
    //Customer类中没有定义serialVersionUID
    private String name;
    private int age;

    //新添加的sex属性
    private String sex;
    
    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    /*
     * @MethodName toString
     * @Description 重写Object类的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

然后执行反序列操作,此时就会抛出如下的异常信息:

 Exception in thread "main" java.io.InvalidClassException: Customer; 

意思就是说,文件流中的class和classpath中的class,也就是修改过后的class,不兼容了,处于安全机制考虑,程序抛出了错误,并且拒绝载入。那么如果我们真的有需求要在序列化后添加一个字段或者方法呢?应该怎么办?那就是自己去指定serialVersionUID。在TestSerialversionUID例子中,没有指定Customer类的serialVersionUID的,那么java编译器会自动给这个class进行一个摘要算法,类似于指纹算法,只要这个文件 多一个空格,得到的UID就会截然不同的,可以保证在这么多类中,这个编号是唯一的。所以,添加了一个字段后,由于没有显指定 serialVersionUID,编译器又为我们生成了一个UID,当然和前面保存在文件中的那个不会一样了,于是就出现了2个序列化版本号不一致的错误。因此,只要我们自己指定了serialVersionUID,就可以在序列化后,去添加一个字段,或者方法,而不会影响到后期的还原,还原后的对象照样可以使用,而且还多了方法或者属性可以用。

  下面继续修改Customer类,给Customer指定一个serialVersionUID,修改后的代码如下:

class Customer implements Serializable {
    /**
     * Customer类中定义的serialVersionUID(序列化版本号)
     */
    private static final long serialVersionUID = -5182532647273106745L;
    private String name;
    private int age;

    //新添加的sex属性
    //private String sex;
    
    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    /*public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }*/

    /*
     * @MethodName toString
     * @Description 重写Object类的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

重新执行序列化操作,将Customer对象序列化到本地硬盘的Customer.txt文件存储,然后修改Customer类,添加sex属性,修改后的Customer类代码如下:

class Customer implements Serializable {
    /**
     * Customer类中定义的serialVersionUID(序列化版本号)
     */
    private static final long serialVersionUID = -5182532647273106745L;
    private String name;
    private int age;

    //新添加的sex属性
    private String sex;
    
    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    /*
     * @MethodName toString
     * @Description 重写Object类的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

执行反序列操作,这次就可以反序列成功了




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值