ObjectInputStream

Java ObjectInputStream and ObjectOutputStream Example

In this example we will see how we can use Java’s ObjectInputStream and ObjectOutputStream classes to serialize objects and store them as a file or any other storage accessible by Output Stream; read them again, deserialize it into an object and use it.

ObjectOutputStream Example

So, first we will see how to write an object into a File using FileOutputStream object. We will wrap FileOutputStream in a ObjectOutputStream and write into the file using ObjectOutputStream's writeObject() method.
 

Important thing to not here is that the object which is to be serialised needs to implement java.io.Serializable interface and hence implement the toString() method.

Lets see this in example :

User.java

package com.javacodegeeks.example;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * @author anirudh
	 */
	private static final long serialVersionUID = 8309080721495266420L;
	private String firstName;
	private String lastName;
	private String email;

	public User(String firstName, String lastName, String email) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}

	//..getters and setters...

	/**
	 * Two users are equal if their firstName, lastName and email address is
	 * same.
	 */
	@Override
	public boolean equals(Object obj) {
		return (this.firstName.equals(((User) obj).firstName)
				&& this.lastName.equals(((User) obj).lastName) && this.email
					.equals(((User) obj).email));
	}

	@Override
	public String toString() {
		return getFirstName() + " " + getLastName() + " " + getEmail();
	}

}

JavaObjectInputOutputStreamExample.java

package com.javacodegeeks.example;

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

/**
 * 
 * @author anirudh
 */
public class JavaObjectInputOutputStreamExample {

	public static void main(String[] args) {

		try {

			// Store Serialized User Object in File
			FileOutputStream fileOutputStream = new FileOutputStream(
					"/Users/anirudh/user.txt");
			User user = new User("Anirudh", "lastName", "email");
			ObjectOutputStream output = new ObjectOutputStream(fileOutputStream);
			output.writeObject(user);
			output.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}

}

ObjectInputStream Example

In the above example we wrote the user object into a file. In order to read from this file , we will use ObjectInputStream. This class enables us to read Java Objects from InputStream instead of only bytes. We can wrap an InputStream in a ObjectInputStream and then can read objects from it.

Lets see this in the example :

JavaObjectInputOutputStreamExample.java

package com.javacodegeeks.example;

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

/**
 * 
 * @author anirudh
 * 
 */
public class JavaObjectInputOutputStreamExample {

	public static void main(String[] args) {

		try {

			//Read from the stored file
			FileInputStream fileInputStream = new FileInputStream(new File(
					"/Users/anirudh/test.txt"));
			ObjectInputStream input = new ObjectInputStream(fileInputStream);
			User user2 = (User) input.readObject();
			System.out.println(user2.getFirstName());
			input.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Output :

Anirudh

In the example we read a file which was previously written by ObjectOutputStream as a serialised object. Here, we have deserialised it using ObjectInputStream.readObject() method.

This was an example of using ObjectInputStream and ObjectOutputStream classes in Java.

Download
You can download the full source code of this example here : JavaObjectInputOutputStreamExample.zip

Anirudh Bhatnagar

Anirudh is a Java programmer with extensive experience in building Java/J2EE applications. He has always been fascinated by the new technologies and emerging trends in software development. He has been involved in propagating these changes and new technologies in his projects. He is an avid blogger and agile enthusiast who believes in writing clean and well tested code.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button