Serializing Java Objects - Java File Path IO

Java examples for File Path IO:Serialization

Introduction

To serialize a class so that you can restore it.

Demo Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
  public static void main(String[] args) {
    Main example = new Main();
    example.start();/* w ww  .j  a  v  a2 s . c  o m*/
  }

  private void start() {
    MyClass settings = new MyClass("The title of the application");
    saveSettings(settings, "settings.bin");
    MyClass loadedSettings = loadSettings("settings.bin");
    if (loadedSettings != null)
      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 Serializable {

  private String title;

  public MyClass() {

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

  public String getTitle() {
    return title;
  }

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

Result


Related Tutorials