Java Serialization Introduction .

What you need to know before this learning.

  • You should have learned and understood everything under Java Basic.
Java Serialization
  • Whenever an java object is to be sent over the network, and moreover if the state of an object is to be saved, java objects need to be serialized.
  • With Serializing we mean to convert a java object to a stream of data. It is also known as a marshalling process.
  • A serialized object contains the information necessary to deserialize or unmarshal, the object.
  • The java.io.ObjectOutputStream and java.io.ObjectInputStream classes are used to write and read objects on any type of existing I/O streams.

How to serialize java object to a file:

  • To write a serialized java object to a file, create an java.io.ObjectOutputStream from a java.io.FileOutputStream.
    (The data in the file is in a proprietary Java format, so it will be difficult for you to read it)
    // Serialize today’s date to a file.
    java.io.FileOutputStream f = new java.io.FileOutputStream("tmp");
    java.io.ObjectOutputStream s = new java.io.ObjectOutputStream(f);
    s.writeObject("Today");
    s.writeObject(new Date());
    s.flush();
    You will find more details about this here.

How to serialize java object to another Java program:

  • To write a serialized java object to another Java program, retrieve the java.io.OutputStream from a java.net.Socket and create the java.io.ObjectOutputStream from that.
    (The other Java program will re-create the object when reading it)
    Socket socket = new Socket("someHost", 2201);
    OutputStream OutStream = socket.getOutputStream();
    java.io.ObjectOutputStream stream = new java.io.ObjectOutputStream(OutStream);
    stream.writeObject("Today");
    stream.writeObject(new java.util.Date());
    stream.flush();

How to serialize java object to a byte array:

  • To write a serialized java object to a byte array, create a java.io.ByteArrayOutputStream and wrap an java.io.ObjectOutputStream around it.
    (This array could then be stored in a DBMS)
    java.io.ByteArrayOutputStream bstream= new java.io.ByteArrayOutputStream();
    java.io.ObjectOutputStream st = new java.io.ObjectOutputStream(bstream);
    st.writeObject("This is a test string");
    st.flush();
    byte[] bytes=bstream.toByteArray();
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.