Serialization in Java

Serialization is a very cool concept in Java, allowing you to save any object that is serializable to a file, and call it back later. This can be useful for a number of reason, perhaps if you want to make a save file for a game, or have a database that you want to access later. It’s a very useful tool, and pretty easy to implement. Let me walk you through the basics of getting started in serialization.

What objects are serializable?

Almost all object classes in Java that you would want to serialize are already serializable.

How can I make a class I write construct serializable objects?

By changing two little lines of code, that how. First, have this at the top of your class file:

import java.io.Serializable;

and when declaring your class, you have to implement the Serializable interface. it is what is known as a marker interface, meaning there is no code in it, it just lets Java know that it can serialize that object.

How do I output a serializable object to a file?

First, make sure you have this statement at the top of your class:
import java.io.*

then, we are going to use two of the classes in the IO package, ObjectOutputStream and FileOutputStream. here is an example block of code, where we will use a class from a game simply called Player, and save it to a file.


Player playerOne=new Player();
String fileName="save.txt";
try{
FileOutputStream fos=new FileOutputStream(fileName);
ObjectOutputStream out=new ObjectOutputStream(fos);
out.writeObject(playerOne);
out.close();
}
catch(IOException e){
e.printStackTrace();
}

A few things to note here:

  • You must construct both a FileOutputStream and an ObjectOutputStream, and wrap them as shown.
  • When you are done writing to the file, you must call the close() method, otherwise the file will not save properly.
  • You have to use these in a try catch block, and catch an IOException.
  • your file doesn’t have to be in *.txt format. you can use any 3-letter extension.

How do I retrieve an object that has been serialized?

The syntax is very similar to above. this time we are using the ObjectInputStream and FileInputStream classes. here’s an example:


Player playerOne;
String fileName="save.txt";
try{
FileInputStream fis=new FileInputStream(fileName);
ObjectInputStream ois=new ObjectInputStream(fis);
playerOne = (Player) ois.readObject();
ois.close()
}
catch(IOException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}

As you can see, the syntax is nearly the same. take note of the fact that you have to cast the object when you read from the file. You also have another exception to check for, one that may be unfamiliar to you.

So there you go! I’m sure you will find a lot of ways to implement this technique in plenty of your applications!

Leave a Reply