Externalizable接口的用法

类别:Java 点击:0 评论:0 推荐:

Externalizable接口继承了Serializable接口,用来在序列化时手动的把需要的对象信息进行序列化。
Externalizable接口提供了两个方法:writeExternal(ObjectOuput out) 和 readExternal(ObjectInput in)
在你需要被序列化的类中实现这两个方法,这样在此类序列化时这两个方法将被自动执行,用以可定制地序列化此类。举例如下:
假如你需要序列化一个类Test:
import java.io.*;

class Test implements Externalizable{  //Test类必须实现Externalizable接口
 private String letterstates = "fanruijun";
 private int num  = 0;
 public Test(){
 }
 
 public void writeExternal(ObjectOutput out) throws IOException {
              out.writeObject(letterstates);
              out.write(88); //在序列化的数据最后加个88
 }

 public void readExternal(ObjectInput in) throws IOException,
    ClassNotFoundException {
                letterstates = (String)in.readObject();
                num = in.read();  //把数字88加进来
 }
 public void putOut(){ //测试
   System.out.println(letterstates +num);
 }
}


序列化上面的Test类:AppTest

import java.io.*;

public class AppTest {


        private void saveGame(){
                Test m = new Test();
                if (m != null){
                        try{
                                FileOutputStream ostream = new FileOutputStream("t.txt");
                                ObjectOutputStream p = new ObjectOutputStream(ostream);

                                p.writeObject(m); //writeExternal()自动执行

                                p.flush();
                                ostream.close();
                        } catch (IOException ioe) {
                                System.out.println ("Error saving file:");
                                System.out.println (ioe.getMessage());
                        }
                }
        }

        private void loadGame(){
                try{
                        FileInputStream instream = new FileInputStream("t.txt");
                        ObjectInputStream p = new ObjectInputStream(instream);
                        Test m = (Test)p.readObject();//readExternal()自动执行
               
   m.putOut();
                        instream.close();
                } catch (Exception e) {
                        System.out.println ("Error loading file:");
                        System.out.println (e.getMessage());
  }
        }

 public static void main(String[] args){
  new AppTest().saveGame();
  new AppTest().loadGame();
 }
}

运行结果:
D:\test\basic>javac AppTest.java

D:\test\basic>javac Test.java

D:\test\basic>java AppTest
fanruijun88

本文地址:http://com.8s8s.com/it/it14814.htm