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 the object into a file.

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

1. Address.java

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

package com.mkyong.io;
 
import java.io.Serializable;
 
public class Address implements Serializable{
 
	   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. Serializer.java

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

package com.mkyong.io;
 
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
public class Serializer {
 
   public static void main (String args[]) {
 
	   Serializer serializer = new Serializer();
	   serializer.serializeAddress("wall street", "united state");
   }
 
   public void serializeAddress(String street, String country){
 
	   Address address = new Address();
	   address.setStreet(street);
	   address.setCountry(country);
 
	   try{
 
		FileOutputStream fout = new FileOutputStream("c:\\address.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fout);   
		oos.writeObject(address);
		oos.close();
		System.out.println("Done");
 
	   }catch(Exception ex){
		   ex.printStackTrace();
	   }
   }
}

Please read this article about how to read the saved object from file.

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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