jedistar
asked on
Serialization
How do you do Serialization, any sample codes?
what is it for too..
what is it for too..
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
From JDK 1.4 you can serialize in XML also:
import java.util.Vector;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStr eam;
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(toSeri alize);
encoder.flush();
System.out.println("out:\n "+out.toSt ring());
}
}
produces:
out:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_06" class="java.beans.XMLDecod er">
<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>
import java.util.Vector;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStr
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(toSeri
encoder.flush();
System.out.println("out:\n
}
}
produces:
out:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2_06" class="java.beans.XMLDecod
<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.s er");
ObjectOutputStream out = new ObjectOutputStream(fileOut );
out.writeObject(objectToBe Serialized );
out.close();
fileOut.close();
ObjectOutputStream out = new ObjectOutputStream(fileOut
out.writeObject(objectToBe
out.close();
fileOut.close();
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