
views
Open the Java coding object that requires serialization or create one from scratch.
Select the object in Java that you want to serialize. In this example, we will call that object “MyObject.”
Enable object serialization in Java by making the MyObject class to implement the java.io.Serialize interface. Just add the following code line at the beginning of the code, replacing the "public class MyObject" line.public class MyObject implements java.io.Serializable
Now your object is serializable, that means that it can be written by an output stream, like this: The following code lines illustrate how to write MyObject (or any serializable object) to a file or disk. try{ // Serialize data object to a file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyObject.ser")); out.writeObject(object); out.close(); // Serialize data object to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(object); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { }
It can be read like this: try{ FileInputStream door = new FileInputStream("name_of_file.sav"); ObjectInputStream reader = new ObjectInputStream(door); MyObject x = new MyObject(); x = (MyObject) reader.nextObject();}catch (IOException e){ e.printStackTrace();}Serialize an Object in Java Step 6 Version 3.jpg
Execute the serialized object code within the Java program to make sure that it operates effectively (optional).
Save and close the serialized object in Java.
Comments
0 comment