Tutorial

ObjectOutputStream in Java - write Object to File

Published on August 4, 2022
author

Pankaj

ObjectOutputStream in Java - write Object to File

ObjectOutputStream in Java can be used to convert an object to OutputStream. The process of converting object to stream is called serialization in java. Once an object is converted to Output Stream, it can be saved to file or database, send over the network or used in socket connections. So we can use FileOutputStream to write Object to file.

ObjectOutputStream

ObjectOutputStream is part of Java IO classes and its whole purpose is to provide us a way to convert java object to a stream. When we create an instance of ObjectOutputStream, we have to provide the OutputStream to be used. This OutputStream is further used by ObjectOutputStream to channel the object stream to underlying output stream, for example, FileOutputStream.

ObjectOutputStream requirement

The object that we want to serialize should implement java.io.Serializable interface. Serializable is just a marker interface and doesn’t have any abstract method that we have to implement. We will get java.io.NotSerializableException if the class doesn’t implement Serializable interface. Something like below exception stack trace.

java.io.NotSerializableException: com.journaldev.files.EmployeeObject
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
	at com.journaldev.files.ObjectOutputStreamExample.main(ObjectOutputStreamExample.java:21)

Java ObjectOutputStream Example to write object to file

Le,t’s look at java ObjectOutputStream example to write an object to file. For that first of all, we should have a class with some properties. Let’s create an Object that we will save into the file.

package com.journaldev.files;

import java.io.Serializable;

public class Employee implements Serializable {

	private static final long serialVersionUID = -299482035708790407L;

	private String name;
	private String gender;
	private int age;

	private String role;
	// private transient String role;

	public Employee(String n) {
		this.name = n;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public int getAge() {
		return age;
	}

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

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + " Role=" + this.role;
	}

}

Notice that it’s not a requirement to have getter/setter for all the properties. Or to have a no-argument constructor. As you can see that above Employee object doesn’t have getter/setter methods for “name” property. It also doesn’t have a no-argument constructor. Here is the program showing how to write Object to file in java using ObjectOutputStream.

package com.journaldev.files;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamExample {

	public static void main(String[] args) {
		Employee emp = new Employee("Pankaj");

		emp.setAge(35);
		emp.setGender("Male");
		emp.setRole("CEO");
		System.out.println(emp);
		
		try {
			FileOutputStream fos = new FileOutputStream("EmployeeObject.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			// write object to file
			oos.writeObject(emp);
			System.out.println("Done");
			// closing resources
			oos.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Below image shows the output of the above program. java ObjectOutputStream example to write object to file If you are wondering what is the content of EmployeeObject.ser file, it’s a bit garbled and something like below.

��srcom.journaldev.files.Employee�����yyIageLgendertLjava/lang/String;Lnameq~Lroleq~xp#tMaletPankajtCEO

ObjectOutputStream with a transient

If we don’t want some object property to be converted to stream, we have to use the transient keyword for that. For example, just change the role property like below and it will not be saved.

private transient String role;

ObjectOutputStream and serialVersionUID

Did you noticed the serialVersionUID defined in the Employee object? It’s used by ObjectOutputStream and ObjectInputStream classes for write and read object operations. Although it’s not mandatory to have this field, but you should keep it. Otherwise anytime you change your class that don’t have effect on earlier serialized objects, it will start failing. For a detailed analysis, go over to Serialization in Java. If you are wondering whether our program worked fine or not, use below code to read an object from the saved file.

FileInputStream is = new FileInputStream("EmployeeObject.ser");
ObjectInputStream ois = new ObjectInputStream(is);
Employee emp = (Employee) ois.readObject();

ois.close();
is.close();
System.out.println(emp.toString());
//Output will be "Employee:: Name=Pankaj Age=35 Gender=Male Role=CEO"

That’s all about java ObjectOutputStream and how to use it to write the object to file.

You can checkout more Java IO examples from our GitHub Repository.

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 4, 2020

This is my problem. Why the file should content this? ��srcom.journaldev.files.Employee�����yyIageLgendertLjava/lang/String;Lnameq~Lroleq~xp#tMaletPankajtCEO It should contain, as per my requirement -> Name=“Pankaj” Age=“35” Gender=“Male” Can you please help?

- Anirban

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 10, 2020

    any real time example…?

    - Dipti

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 30, 2015

      Why do we have to implement the serialisable interface while working with hibernate?

      - violet

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 1, 2014

        what is the use of private static final long serialVersionUID = -299482035708790407L;

        - Naveen J

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Featured on Community

          Get our biweekly newsletter

          Sign up for Infrastructure as a Newsletter.

          Hollie's Hub for Good

          Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

          Become a contributor

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          Welcome to the developer cloud

          DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

          Learn more