* utilize ObjectOutputStream Class to serialize objects ,ObjectInputStream Class to deserialize objects .
* Objects that implement serialization must implement Serializable Interface , Provide global constants serialVersionUID, And all its properties are serializable .
* Using object serialization, you can quickly make a deep copy of an object . import java.io.*; public class SerializableTest {
public static void main(String[] args) { // Object serialization ObjectOutputStream outputStream
= null; try { outputStream = new ObjectOutputStream(new FileOutputStream(
"D:\\Desktop\\Files\\Object.dat", true)); outputStream.writeObject(new Test1(
"Test1", 1, new Test2("Test2", 2))); outputStream.flush(); } catch (IOException
e) { e.printStackTrace(); } finally { if (outputStream != null) { try {
outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
// Object deserialization ObjectInputStream inputStream = null; try { inputStream = new
ObjectInputStream(new FileInputStream("D:\\Desktop\\Files\\Object.dat")); Test1
test1= (Test1) inputStream.readObject(); System.out.println(test1); } catch (
IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.
printStackTrace(); } finally { if (inputStream != null) { try { inputStream.
close(); } catch (IOException e) { e.printStackTrace(); } } } // Object deep copy try {
Test1 test1 = new Test1("Test1", 10, new Test2("Test2", 20));
ByteArrayOutputStream data = new ByteArrayOutputStream(); outputStream = new
ObjectOutputStream(data); outputStream.writeObject(test1); inputStream = new
ObjectInputStream(new ByteArrayInputStream(data.toByteArray())); Test1 test2 = (
Test1) inputStream.readObject(); System.out.println(test1); System.out.println(
test2); System.out.println(test1 == test2); } catch (IOException e) { e.
printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }
finally { if (outputStream != null) { try { outputStream.close(); } catch (
IOException e) { e.printStackTrace(); } } if (inputStream != null) { try {
inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
class Test1 implements Serializable { private static final long serialVersionUID
= -7300046014501169240L; private String str; private int value; private Test2
test2; public Test1(String str, int value, Test2 test2) { this.str = str; this.
value= value; this.test2 = test2; } @Override public String toString() { return
"Test1{" + "str='" + str + '\'' + ", value=" + value + ", test2=" + test2 + '}';
} } class Test2 implements Serializable { private static final long
serialVersionUID= 3341032494948326316L; private String str; private int value;
public Test2(String str, int value) { this.str = str; this.value = value; }
@Override public String toString() { return "Test2{" + "str='" + str + '\'' +
", value=" + value + '}'; } }

Technology