集册 Java实例教程 更有效地序列化Java对象

更有效地序列化Java对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

602
实现externalizable接口,并指示Java使用readExternal / writeExternal方法提供的自定义序列化/反序列化机制。

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Point;

import java.io.Externalizable;
/* 
 来自 
*nowjava.com - 时代Java*/

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInput;

import java.io.ObjectInputStream;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;


public class Main {

  public static void main(String[] args) {
  /*
   from 时 代 J a v a - nowjava.com 
  */

    Main example = new Main();

    example.start();

  }


  private void start() {

    MyClass settings = new MyClass("The title of the application");

    saveSettings(settings, "settingsExternalizable.bin");

    MyClass loadedSettings = loadSettings("settingsExternalizable.bin");

    System.out.println("Are settings are equal? :"

        + loadedSettings.equals(settings));


  }


  private void saveSettings(MyClass settings,

      String filename) {

    try {

      FileOutputStream fos = new FileOutputStream(filename);

      try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {

        oos.writeObject(settings);

      }

    } catch (IOException e) {

      e.printStackTrace();

    }

  }


  private MyClass loadSettings(String filename) {

    try {

      FileInputStream fis = new FileInputStream(filename);

      ObjectInputStream ois = new ObjectInputStream(fis);

      return (MyClass) ois.readObject();

    } catch (IOException | ClassNotFoundException e) {

      e.printStackTrace();

    }

    return null;

  }

}


class MyClass implements Externalizable {

  private String title;

  public MyClass() {

  }


  @Override

  public void writeExternal(ObjectOutput out) throws IOException {

    out.writeUTF(title);

  }


  @Override

  public 
展开阅读全文