How to write an Object to file in Java

Java object can write into a file for future access, this is called Serialization. In order to do this, you have to implement the Serializableinterface, and use ObjectOutputStream to write objects into a file.


FileOutputStream fout = new FileOutputStream("c:\\temp\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);

1. Object

Create an “Address” object and implement the Serializable interface. This object is going to write into a file.

Address.java

package com.mkyong.io;

import java.io.Serializable;

public class Address implements Serializable {

	private static final long serialVersionUID = 1L;

	String street;
	String country;

	public void setStreet(String street) {
		this.street = street;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getStreet() {
		return this.street;
	}

	public String getCountry() {
		return this.country;
	}

	@Override
	public String toString() {
		return new StringBuffer(" Street : ")
				.append(this.street).append(" Country : ")
				.append(this.country).toString();
	}

}

2. Write Object to File

This class will write the “Address” object and it’s variable value (“wall street”, “united state”) into a file named c:\\temp\\address.ser

WriteObject.java

package com.mkyong.io;

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

public class WriteObject {

	public static void main(String args[]) {

		WriteObject obj = new WriteObject();

		Address address = new Address();
		address.setStreet("wall street");
		address.setCountry("united state");

		obj.serializeAddress(address);

	}

	public void serializeAddress(Address address) {

		FileOutputStream fout = null;
		ObjectOutputStream oos = null;

		try {

			fout = new FileOutputStream("c:\\temp\\address.ser");
			oos = new ObjectOutputStream(fout);
			oos.writeObject(address);

			System.out.println("Done");

		} catch (Exception ex) {

			ex.printStackTrace();

		} finally {

			if (fout != null) {
				try {
					fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public void serializeAddressJDK7(Address address) {

		try (ObjectOutputStream oos = 
				new ObjectOutputStream(new FileOutputStream("c:\\temp\\address2.ser"))) {

			oos.writeObject(address);
			System.out.println("Done");

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}
Note
Please read this article about how to read the saved object from file – Java.

References

  1. ObjectOutputStream JavaDoc
  2. Java Object Serialization
  3. try-with-resources example in JDK 7

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Jeff
Guest
Jeff

Mkyong always bringing up the real world examples and a solution for it.
You help me a lot with your posts.
Thank you very much.
keep up with your work.

Hitesh Garg
Guest
Hitesh Garg

That’s a good example from a coders point of but very less explanation.

I would recommend you to visit this for a much better explanation and examples.

http://www.codingeek.com/java/io/object-streams-serialization-deserialization-java-example-serializable-interface/

Manjeet
Guest
Manjeet

my file is having junk character after file writing is done :-(
how to fix it ??

hussey
Guest
hussey

///to read multiple objects from file

class Deserializer{

public static void main (String args[]) throws ClassNotFoundException, IOException {
Deserializer deserializer = new Deserializer();
ArrayList arraylist=deserializer.deserialzeAddress();
System.out.println(arraylist.toString());
}

public ArrayList deserialzeAddress() throws IOException, ClassNotFoundException{
Address address;
ArrayList arraylist=new ArrayList();
ObjectInputStream ois = null;
FileInputStream fin = null;
try{
fin = new FileInputStream(“e:\address.ser”);
if(fin.available()!=0)
{
while (true) {
ois = new ObjectInputStream(fin);
arraylist.add((Address)ois.readObject());
}}}catch (EOFException e) {
// as expected
} finally {
if (fin != null)
ois.close();
System.out.println(arraylist.size());
return arraylist;
}
}
}

Merouane Tchikaoui
Guest
Merouane Tchikaoui

Are these lines valable for append (add at the end) of file?

Jeff
Guest
Jeff

This code doesn’t compile.

Alexander_Ochs
Guest
Alexander_Ochs

Thank you =)

Shane
Guest
Shane
@Amy, @ Manjeet: The file will be garbled as it wont save it directly in ASCII readable characters. It will convert it to a serialized binary stream, when you view that stream in the file it won’t be readable (but thats normal). If you read the file back into an object the data will be the same. @Mitrajit: You best off creating an object for yor 3D data that will store your geometry such as X, Y, Z, type of object, size or object, etc and then saving that object to file rather than saving the physical entity. @mkyong: Thanks… Read more »
Mitrajit Samanta
Guest
Mitrajit Samanta

Thanks for your tutorial, its really helpful.

your program runs perfectly with string data, but what if we use java3d object such as ColorCube, Sphere….?
I have a java3d program that needs to be write various java3d objects in a object file for later use. But I can’t do it. Please help me.

Amy Xiao
Guest
Amy Xiao

Good tutorial~~
But the file is garbled, how to fix this?

trackback
Anonymous

[…] […]

trackback
How to compress serialized object into file | Java

[…] file Written on January 25, 2010 at 2:07 am by mkyong In last section, you learn about how to write or serialized an object into a file. In this example , you can do more than just serialized it , you also can compress the serialized […]

trackback
How to read an Object from file in Java | Java

[…] Java Written on January 10, 2010 at 8:50 am by mkyong In previous example, you learn how to write an Object into a file in Java. In this example, you will learn how to read an Object from the saved file or how to deserialize […]