Searching...
Thursday, 20 September 2012

Java Serialization / DeSerialization Example

04:49
Java program to serialize and deserialize objects
package mycollectiontest;

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

public class SerializationExample {

public static void main(String[] args) {
Customer customer = new Customer("Vinod", "Bangalore");

FileOutputStream fos;
try {
// Serialization
fos = new FileOutputStream(new File("customer.ser"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(customer);
oos.flush();
oos.close();

// Deserialization
FileInputStream fis = new FileInputStream("customer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Customer decustomer = (Customer) ois.readObject();
ois.close();
System.out.println("Customer after serialization: " + decustomer);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

class Customer implements Serializable {
/**
   *
   */
private static final long serialVersionUID = -1943599317632365868L;
private String name;
private String address;

public Customer(String name, String address) {
super();
this.name = name;
this.address = address;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Customer [name=" + name + ", address=" + address + "]";
}

}
Output
Customer after serialization: Customer [name=Vinod, address=Bangalore]

 

 

0 comments: