How to Serialize an Object in Java

Open the Java coding object that requires serialization or create one from scratch., Select the object in Java that you want to serialize., Enable object serialization in Java by making the MyObject class to implement the java.io.Serialize...

9 Steps 1 min read Medium

Step-by-Step Guide

  1. Step 1: Open the Java coding object that requires serialization or create one from scratch.

    In this example, we will call that object “MyObject.” , 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 , 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) { } ,,,
  2. Step 2: Select the object in Java that you want to serialize.

  3. Step 3: Enable object serialization in Java by making the MyObject class to implement the java.io.Serialize interface.

  4. Step 4: Now your object is serializable

  5. Step 5: that means that it can be written by an output stream

  6. Step 6: like this: The following code lines illustrate how to write MyObject (or any serializable object) to a file or disk.

  7. Step 7: 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(); }

  8. Step 8: Execute the serialized object code within the Java program to make sure that it operates effectively (optional).

  9. Step 9: Save and close the serialized object in Java.

Detailed Guide

In this example, we will call that object “MyObject.” , 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 , 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) { } ,,,

About the Author

C

Christina Harris

Experienced content creator specializing in hobbies guides and tutorials.

80 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: