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.



[...] 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 [...]
[...] 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 [...]