码迷,mamicode.com
首页 > 编程语言 > 详细

java的序列化之Externalizable接口

时间:2015-09-17 23:19:15      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

控制序列化字段还可以使用Externalizable接口替代Serializable借口。此时需要定义一个默认构造器,否则将为得到一个异常(java.io.InvalidClassException: Person; Person; no 

valid constructor);还需要定义两个方法(writeExternal()和readExternal())来控制要序列化的字段。 
在Person类中

package com.kc.iotest02;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable {

    private String name;
    private int age;
    /**
     * 必须有无参数的构造器
     */
    public Person() {
    System.out.println("无参数的构造器");
    }
    public Person(String name,int age) {
        System.out.println("带参数的构造器");
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "姓名是"+name+"年龄是"+age;
    }
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        // TODO Auto-generated method stub

        out.writeObject(name);
        out.writeObject(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        // TODO Auto-generated method stub
        this.name=(String)in.readObject();
        this.age=(int)in.readObject();
    }

}

测试类中代码

public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        FileOutputStream fos=null;
        ObjectOutputStream oos=null;
        FileInputStream fis=null;
        ObjectInputStream ois=null;
        try {
            fos=new FileOutputStream(new File("E://javanewlskd.txt"));
            oos=new ObjectOutputStream(fos);
            oos.writeObject(new Person("孙悟空",600));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(oos!=null) {
                oos.close();
            }
        }
        
        try {
            fis=new FileInputStream(new File("E://javanewlskd.txt"));
            ois=new ObjectInputStream(fis);
            Person per=(Person)ois.readObject();
            System.out.println(per);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(ois!=null) {
                ois.close();
            }
        }
        
        
        
    }

 

java的序列化之Externalizable接口

标签:

原文地址:http://www.cnblogs.com/dukc/p/4817822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!