Skip to content

Instantly share code, notes, and snippets.

@madan712
Created January 3, 2013 10:29
Show Gist options
  • Save madan712/4442476 to your computer and use it in GitHub Desktop.
Save madan712/4442476 to your computer and use it in GitHub Desktop.
In SerializeDog.java we will create a Dog object d1 serialize it and write it to a dog.ser file and latter we will deserialize the object.
/* SerializeDog.java */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeDog {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.setName("Tommy");
// Serialization
try {
FileOutputStream fs = new FileOutputStream("c:/dog.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(d1);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
Dog d2 = null;
// Deserialization
try {
FileInputStream fis = new FileInputStream("c:/dog.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
d2 = (Dog) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Deserialization dog " + d2);
System.out.println("name = " + d2.getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment