SERIALIZATION CUSTOMER:
An Object can be directly saved into a file and can be later reloaded. This process is called Serialization and the restoration is called De-serialization. The extension of the file is ".ser".
An Object is considered ready for serialization if its class implements a Serializable interface.
The serializable interface is called Marker Interface. A Marker Interface is one that has no methods and member variables, but just indicates / marks that the given class is implementing the Interface.
Use ObjectOutputStream class for converting an object to a serialized file.
Input and Output Format:
Enter the Customer name
John
Enter the Customer number
12
Enter the Customer address
Chennai
CODE:
import java.io.Serializable;
public class Customer implements Serializable {
private String name;
private Integer number;
private String address;
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Customer(String name, Integer number, String address) {
super();
this.name = name;
this.number = number;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args)throws IOException, ClassNotFoundException{
Scanner sc = new Scanner(System.in);
// Customer c = new Customer();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Serialize.ser");
oos = new ObjectOutputStream(fos);
System.out.println("Enter the Customer name");
String name = sc.nextLine();
System.out.println("Enter the Customer number");
int number = Integer.parseInt(sc.nextLine());
System.out.println("Enter the Customer address");
String add = sc.nextLine();
oos.writeObject(new Customer(name,number,add));
oos.flush();
}
catch(Exception e) {
System.out.println(e);
}
finally {
sc.close();
}
}
}
Comments
Post a Comment