Serializing Java Objects More Efficiently - Java File Path IO

Java examples for File Path IO:Serialization

Introduction

Implement the Externalizable interface and instruct the Java to use a custom serialization/deserialization mechanism, as provided by the readExternal/writeExternal methods.

Demo Code

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.io.Externalizable;
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) {
    Main example = new Main();
    example.start();/*from  ww  w . j ava 2s  . c om*/
  }

  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 void readExternal(ObjectInput in) throws IOException,
      ClassNotFoundException {
    title = in.readUTF();
  }

  public MyClass(String title) {
    this.title = title;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }
}

Related Tutorials