手机版
你好,游客 登录 注册
背景:
阅读新闻

Java序列化机制的深入研究

[日期:2012-08-02] 来源:Linux社区  作者:zhaozheng7758 [字体:大 中 小]

6、Java的序列化算法

序列化算法一般会按步骤做如下事情:

◆ 将对象实例相关的类元数据输出。

◆ 递归地输出类的超类描述直到不再有超类。

◆ 类元数据完了以后,开始从最顶层的超类开始输出对象实例的实际数据值。

◆ 从上至下递归输出实例的数据

7、序列化实例介绍

7.1 定制数据格式的序列化

验证怎样用writeObject和readObject方法编码一个定制数据格式。当有大量持久性数据时,数据应该以简洁、精简的格式存放。此例子用一个矩形对称阵列,只对其一半数据序列化,即只写/读一半数据再恢复成完整阵列。

package com.asc.alibaba.base;

 

import java.io.*;

 

publicclass CustomDataExample implements Serializable {

 

    transientintdimension;

    transientintthearray[][];

 

    CustomDataExample(int dim){

        dimension = dim;

        thearray = newint[dim][dim];

        arrayInit();

    }

 

    publicstaticvoid main(String args[]) {

        CustomDataExample corg = new CustomDataExample(4);

        CustomDataExample cnew = null;

        try {

            FileOutputStream fo = new FileOutputStream("cde.tmp");

            ObjectOutputStream so = new ObjectOutputStream(fo);

            so.writeObject(corg);

            so.flush();

            so.close();

        } catch (Exception e) {

            e.printStackTrace();

            System.exit(1);

        }

        try {

            FileInputStream fi = new FileInputStream("cde.tmp");

            ObjectInputStream si = new ObjectInputStream(fi);

            cnew = (CustomDataExample) si.readObject();

            si.close();

        } catch (Exception e) {

            e.printStackTrace();

            System.exit(1);

        }

        System.out.println();

        System.out.println("Printing the original array...");

        System.out.println(corg);

        System.out.println();

        System.out.println("Printing the new array...");

        System.out.println();

        System.out.println(cnew);

        System.out.println();

        System.out.println("The original and new arrays should be the same!");

        System.out.println();

    }

 

    privatevoid writeObject(ObjectOutputStream s) throws IOException {

        /* 先调用缺省的defaultWriteObject()方法保存非临时变元(若有) */

        s.defaultWriteObject();

        /* 对临时变元明确调用原型数据writeInt()方法以保存其 */

        s.writeInt(dimension);

        for (int i = 0; i < dimension; i++) {

            for (int j = 0; j <= i; j++) {

                /* 对临时变元明确调用原型数据writeInt()方法以保存其阵列的一半数据 */

                s.writeInt(thearray[i][j]);

            }

        }

 

    }

 

    privatevoid readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {

        /* 先调用缺省的defaultReadObject()方法恢复非临时数据,再显式调用原型数据readInt()方法恢复临时数据,写入和恢复数据的顺序要求一致 */

        s.defaultReadObject();

        dimension = s.readInt();

        thearray = newint[dimension][dimension];

        for (int i = 0; i < dimension; i++) {

            for (int j = 0; j <= i; j++) {

                thearray[i][j] = s.readInt();

            }

        }

        for (int i = 0; i < dimension; i++) {

            for (int j = dimension - 1; j > i; j--) {

                thearray[i][j] = thearray[j][i];

            }

        }

    }

 

    /* 此方法的功能是将阵列作成对角阵 */

    void arrayInit() {

        int x = 0;

        for (int i = 0; i < dimension; i++) {

            for (int j = 0; j <= i; j++) {

                thearray[i][j] = x;

                thearray[j][i] = x;

                x++;

            }

        }

    }

 

    public String toString() {

 

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < dimension; i++) {

            for (int j = 0; j < dimension; j++) {

 

                sb.append(Integer.toString(thearray[i][j]) + " ");

            }

            sb.append("\n");

        }

        return (sb.toString());

    }

}

结果如下:

  Printing the original array...

0 1 3 6

1 2 4 7

3 4 5 8

6 7 8 9

Printing the new array...

0 1 3 6

1 2 4 7

3 4 5 8

6 7 8 9

The original and new arrays should be the same!

7.2 非序列化超类的序列化

当一个已序列化的子类的超类没有序列化时,子类必须显式存储超类的状态。

/* NonSerialSuperExample */

package com.asc.alibaba.base;

 

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

 

publicclass NonSerialSuperExample {

 

    publicstaticvoid main(String args[]) {

        Book bookorg = new Book(100, "How to Serialize", true, "R.R", "Serialization", 97);

        Book booknew = null;

        try {

            FileOutputStream fo = new FileOutputStream("tmp");

            ObjectOutputStream so = new ObjectOutputStream(fo);

            so.writeObject(bookorg);

            so.flush();

        } catch (Exception e) {

            System.out.println(e);

            System.exit(1);

        }

        try {

            FileInputStream fi = new FileInputStream("tmp");

            ObjectInputStream si = new ObjectInputStream(fi);

            booknew = (Book) si.readObject();

        } catch (Exception e) {

            System.out.println(e);

            System.exit(1);

        }

        System.out.println();

        System.out.println("Printing original book..");

        System.out.println(bookorg);

        System.out.println("Printing new book..");

        System.out.println(booknew);

        System.out.println("Both original and new should be the same");

        System.out.println();

    }

}

/* Book.java */

package com.asc.alibaba.base;

 

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

 

class Book extends ReadingMaterial implements Serializable {

 

    int     numpages;

    String  name;

    booleanishardcover;

 

    public Book(){

        super();

    }

 

    public Book(int pages, String n, boolean hardcover, String author, String subject, int yearwritten){

        super(author, subject, yearwritten);

        numpages = pages;

        name = n;

        ishardcover = hardcover;

    }

 

    privatevoid writeObject(ObjectOutputStream out) throws IOException {

        out.defaultWriteObject();

        out.writeObject(author);

        out.writeObject(subject);

        out.writeInt(yearwritten);

    }

 

    privatevoid readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

 

        in.defaultReadObject();

 

        author = (String) in.readObject();

        subject = (String) in.readObject();

        yearwritten = in.readInt();

    }

 

    public String toString() {

        return ("Name:" + name + "\n" + "Author:" + author + "\n" + "Pages:" + numpages + "\n" + "Subject:" + subject

                + "\n" + "Year:" + yearwritten + "\n");

    }

}/* ReadingMaterial.java */

 package com.asc.alibaba.base;

 

class ReadingMaterial {

 

    protected String author;

    protected String subject;

    protectedint    yearwritten;

 

    public ReadingMaterial(){

    }

 

    public ReadingMaterial(String auth, String sub, int year){

        author = auth;

        subject = sub;

        yearwritten = year;

    }

}

结果如下: 

Printing original book..

Name:How to Serialize

Author:R.R

Pages:100

Subject:Serialization

Year:97

Printing new book..

Name:How to Serialize

Author:R.R

Pages:100

Subject:Serialization

Year:97

Both original and new should be the same

linux
相关资讯       Java序列化机制  Java序列化 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款