Home ยป Local Data Storage 5 – Reading and Writing Serialized Objects to a File

Share This Post

Featured Tutorials / Java / Tutorial

Serialized Object Files

Morse Code Medphor

Serializing Objects to a File

In this article, we will write some objects to a file then read them back. The objects need to be Serializable. Later in an article, I will show you how to serialize Java to XML and back but standard serialization uses some code that is unreadable. So to make the object file we use.

Working with Java and Files Tutorial Trail
Fixed Width Files XML Data Files

1. Create FiieOutputStream giving it a file name or File Object.
2. Create an ObjectStream giving it the FileOutputStream
3. use objectStream.writeObject(someObject);

To read the object file we use

1. Create FileInputStream and we can give it a file name or File object
2. Create ObjectInputStream using ObjectInputStream
3. use (SomeObject)oubjectInputStream.readObject(someObject) casting it to that object.

If the file contains only one object then we should be fine. If it contains multiple kinds of objects I would assume we need to cast them to the correct objects as they are read in. Meaning we would need to know the order that they are written and read back in. Another thing to note, I had to use a tool called serialver.exe to make the version number for the Expense object. You get this by running ‘serialver’ command and giving it the Expense.class file name. Also if its an inner class you must make it static or it won’t work. Its generally suggested to never use an inner class for this purpose as it may lead to problems, but I did for this example.

A Simple Example

The code below works but it needs file close statements and it throws an exception when it reaches the end of the file. I’ll fix that soon I hope.

import java.io.*;
import java.util.*;

public class ObjectWriterReader {

 public static class Expense implements Serializable {

  private static final long serialVersionUID = -3601370280790552486L;

  public Expense(float amount, Date date, String catagory, String note) {
   this.amount = amount;
   this.date = date;
   this.catagory = catagory;
   this.note = note;
  }
  /**
   * @serial
   */
  float amount = 0.0f;
  /**
   * @serial
   */
  Date date = null;
  /**
   * @serial
   */
  String catagory = "";
  /**
   * @serial
   */
  String note = "";

  public String toString() {
   return "Amount:" + amount + " Date:" + date + " Catagory:" + catagory + " Note:" + note + "\n";
  }
 }
 ArrayList<Expense> expenses = new ArrayList<Expense>();

 public ObjectWriterReader() {
  Expense anExpense = new Expense(22.25f, new Date("10/2/18"), "Clothing", "Jeans");
  expenses.add(anExpense);
  anExpense = new Expense(55.14f, new Date("10/3/18"), "Fuel", "Gas 2.34/gal");
  expenses.add(anExpense);
  anExpense = new Expense(1.08f, new Date("10/5/18"), "Food", "Coffee");
  expenses.add(anExpense);
  anExpense = new Expense(34.25f, new Date("10/9/18"), "Bar", "Food and Drinks");
  expenses.add(anExpense);
  Iterator<Expense> expenseIterator = expenses.iterator();
  try {
   FileOutputStream fos = new FileOutputStream("expenses.dat", true);
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   while (expenseIterator.hasNext()) {
    oos.writeObject((Expense) expenseIterator.next());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  try {
   expenses = new ArrayList<Expense>();
   FileInputStream fis = new FileInputStream("expenses.dat");
   ObjectInputStream ois = new ObjectInputStream(fis);
   Expense expenseObject = null;
   do {
    expenseObject = (Expense) ois.readObject();
    if (expenseObject != null) {
     expenses.add(expenseObject);
    }
   } while (expenseObject != null);
  } catch (Exception e) {
   e.printStackTrace();
  }
  Expense expense = null;
  expenseIterator = expenses.iterator();
  while (expenseIterator.hasNext()) {
   expense = expenseIterator.next();
   System.out.println(expense);
  }
 }

 public static void main(String args[]) {
  new ObjectWriterReader();
 }
}

Share This Post

1 Comment

  1. Ahhh the Zen of Arksoft…I can feel the data flowing through me. ๐Ÿ™‚

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>