Link to home
Start Free TrialLog in
Avatar of jedistar
jedistarFlag for Singapore

asked on

Serialization

How do you do Serialization, any sample codes?
what is it for too..
ASKER CERTIFIED SOLUTION
Avatar of astopheles
astopheles

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of astopheles
astopheles

jedistar -

As to what it can be used for, I should elaborate.  Two popular uses of serialization are:

- Enabling RMI - this is how objects are sent from a local VM to the remote VM

- One way to store information (properties/settings, etc) for an application to disk (instead of creating a text-based format, simply write your setting objects straight to a file and read them in as simply)

Also, here are some more examples straight from Sun:
http://java.sun.com/j2se/1.5.0/docs/guide/serialization/examples/index.html

Cheers,
Astopheles
From JDK 1.4 you can serialize in XML also:


import java.util.Vector;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;

public class Dummy {
    public static void main(String[] args)
    {
        final Vector toSerialize = new Vector();
        toSerialize.add("This is string");
        toSerialize.add(new Integer(1));
        toSerialize.add(new Long(1));
        toSerialize.add(new Double(1));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLEncoder encoder = new XMLEncoder(out);
        encoder.writeObject(toSerialize);
        encoder.flush();

        System.out.println("out:\n"+out.toString());

    }
}


produces:
out:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_06" class="java.beans.XMLDecoder">
 <object class="java.util.Vector">
  <void method="add">
   <string>This is string</string>
  </void>
  <void method="add">
   <int>1</int>
  </void>
  <void method="add">
   <long>1</long>
  </void>
  <void method="add">
   <double>1.0</double>
  </void>
 </object>
FileOutputStream fileOut = new FileOutputStream("MyFile.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(objectToBeSerialized);
out.close();
fileOut.close();