How to Serialize an Object in Java
How to Serialize an Object in Java
When you serialize an object in Java, you convert the data into byte streams that then later convert back into the copy of the original data. If this sounds confusing, think of serialization in the following terms. You're working on a document and then save it to your hard drive. You are, in manner of speaking, serializing the data so you can retrieve that copy later on. Serialization makes the transfer of data on networks much easier and more efficient.It's important that you understand the basics of Java before serializing an object. If you've used programming languages such as Pascal and older versions of C, you'll know that without object serialization, a programmer has to create a separate I/O text file to store and load data. Object serialization in Java bypasses creating this text file to store data, saving time and programming costs. The following article contains the steps to serialize an object in Java. The sample code in this article is used courtesy of The Java Developers Almanac 1.4.
Steps

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.

What's your reaction?

Comments

https://lamidix.com/assets/images/user-avatar-s.jpg

0 comment

Write the first comment for this!