Java serialization and Java deserialization examples

  • 2020-04-01 02:44:55
  • OfStack

Serialization is commonly used in the following scenarios:

1. Permanently save the object, and save the object to the local file through the serialized byte stream;
2. Transfer objects through the network through serialization
3. Pass objects between processes by serialization


import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class javaSerializable_fun {

public static void main(String[] args) {
    try
  {
   //Construct the FileOutputStream object
   FileOutputStream f=new FileOutputStream("C:a.txt");

   //Construct the ObjectOutputStream object
   ObjectOutputStream out=new ObjectOutputStream(f);

   Customer customer=new Customer("bj",50);

   //Serialization is done using the writeObject() method of the ObjectOutputStream object
   out.writeObject(customer);

   //Close the ObjectOutputStream object
   out.close();

   //Close the FileOutputStream object
     f.close();
     System.out.println(" Serialized! ");
  }
  catch(IOException e)
  {
   e.getStackTrace();
  }
}
}
class Customer implements Serializable
{
 private static final long serialVersionUID =1L;

 private String name;
 private int age;

 public String getName()
 {
  return name;
 }

 public int getAge()
 {
  return age;
 }

 public Customer(String name,int age)
 {
  this.name=name;
  this.age=age;
 }

 public String toString()
 {
  return "name="+ name +",age="+age;
 }
}


Related articles: