Serializing objects to binary files in Java 11

For the uninitiated, serialization is when you convert an object instance into some kind of file. There are a couple of kinds of serialization: Json serialization, XML, and others. The kind of serializing we’ll be doing in this tutorial is binary serialization.

Prerequisites: at least one class that can be serialized.

package org.sgrh;

// an example class for the sake of this tutorial
public class Person {
	private String name;
	private String tel;
	private short age;
	private float weightKg;
	private float heightCm;
	
	public Person() {
		this.name = "";
		this.tel = "";
		this.age = 0;
		this.weightKg = 0.0f;
		this.heightCm = 0.0f;
	}
	
	public Person(String name, String tel, short age,
 float weightKg, float heightCm) {
		this.name = name;
		this.tel = tel;
		this.age = age;
		this.weightKg = weightKg;
		this.heightCm = heightCm;
	}

	public String getName() {
		return name;
	}

	public String getTel() {
		return tel;
	}

	public short getAge() {
		return age;
	}

	public float getWeightKg() {
		return weightKg;
	}

	public float getHeightCm() {
		return heightCm;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public void setAge(short age) {
		this.age = age;
	}

	public void setWeightKg(float weightKg) {
		this.weightKg = weightKg;
	}

	public void setHeightCm(float heightCm) {
		this.heightCm = heightCm;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", tel=" + tel +
 ", age=" + age + ", weightKg=" + weightKg + ", heightCm="
				+ heightCm + "]";
	}
	
}

To make this class serializable, we will have to make it implement Serializable.

Changing the Person class to implement the Serializable interface
//Of course, we will also need to import java.io.Serializable
import java.io.Serializable;

public class Person implements Serializable { /*...*/ }

We will immediately receive a compiler warning that the Person class does not have a UID. We will for the sake of brevity ignore this.

We need to add serialize() and deserialize() methods that will allow us to serialize and deserialize our chosen objects. I usually make these static methods and have them be in the same class. Here is a basic serialize() method:

public static void serialize(Person person, String fileName) {
    try {
        //you may also write this verbosely as
        // FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        var fileOutputStream = new FileOutputStream(fileName);
        
        var objOutputStream = new ObjectOutputStream(fileOutputStream);
        
        objOutputStream.writeObject(person);
        //we don't want a memory leak if we can avoid it
        fileOutputStream.close();
        objOutputStream.close();
        
    } catch ( FileNotFoundException e ) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
}

The actual writing of the object happens with objOutputStream.writeObject(ourObjectName); We have to have a FileOutputStream first, however, because the ObjectOutputStream needs to know WHERE it is to output.

The following is some basic code for deserializing() a binary object.

public static Person deserialize(String fileName) {
    Person person = null;
    
    try {
        //could be written as
        // FileInputStream fileInputStream = new 
        //FileInputStream(fileName);
        var fileInputStream = new FileInputStream(fileName);
        var objectInputStream = new ObjectInputStream(fileInputStream);
        
        //read the binary file
        person = (Person) objectInputStream.readObject();
        
        objectInputStream.close();
        fileInputStream.close();
        
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    
    return person;
}

Both the serialize and deserialize methods require quite a few imports from the standard library. Here’s a list:

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

And now, a demonstration of the serialization/de-serialization process with the main class.

program.java opened in Eclipse IDE with program output in the console.
Hello World!
Person [name=John Smith, tel=716-768-2462, age=25, weightKg=68.0389, heightCm=180.3399]
package org.sgrh;


// source code
// Public Domain C00 : No Rights Reserved.

public class program {
	public static void main(String[] args) {
		
		System.out.println("Hello World!");
		
		var person = new Person("Jane Doe", 
				"315-331-1958", 
				(short) 28, 
				54.0389f, 
				164.592f);
		
		//you don't actually have to specify the 
                //.dat file extension.
		//it could be whatever you'd like
		Person.serialize(person, 
                                  "all_the_data.dat");
		
		var person2 = Person.deserialize("anything.dat");
		
		System.out.println(person2.toString());
		
	}
}

Leave a comment