Java Object Serialization
This tutorial explains how to use Java serialization and de-serialization
Table of Contents
- 1. Java serialization
- 2. Example
- 3. About this website
-
- 3.1.
- 4. Links and literature
1. Java serialization
Via Java serialization You can stream your Java object to a sequence of bytes and restore these objects from the this stream of bytes. To make a Java object serializable implement the java.io.Serializable
interface. This is a marker interface which tells the Java platform, the object is serializable.
Certain system-level classes such as Thread
, and its OutputStream
subclasses, and is not Socket
serializable. If you serializable class contains such objects, it must mark then as "transient".
2. Example
Create a Java project called "De.vogella.java.serilization". Create the following Java object called person.
Package De.vogella.java.serilization;import Java.io.serializable;public class Person implements Serializable { Private String firstName; Private String lastName; Stupid example for transient transient private Thread myThread; Public person (string firstName, String lastName) { this.firstname = firstName; This.lastname = LastName; This.mythread = new Thread (); } Public String Getfirstname () { return firstName; } public void Setfirstname (String firstName) { this.firstname = firstName; } Public String Getlastname () { return lastName; } public void Setlastname (String lastName) { this.lastname = lastName; } @Override public String toString () { return ' person [firstname= ' + FirstName + ", lastname=" + lastName + " ]"; }}
The following code example show you how can serializable and de-serializable this object.
package De.vogella.java.serilization;import Java.io.FileInputStream; Import Java.io.fileoutputstream;import Java.io.objectinputstream;import Java.io.objectoutputstream;public class Main {public static void main (string[] args) {String filename = "Time.ser"; Person p = new person ("Lars", "Vogel"); Save the object to file FileOutputStream fos = null; ObjectOutputStream out = null; try {fos = new fileoutputstream (filename); out = new ObjectOutputStream (FOS); Out.writeobject (P); Out.close (); } catch (Exception ex) {ex.printstacktrace (); }//Read the object from File//Save the object to file FileInputStream FIS = null; ObjectInputStream in = null; try {fis = new fileinputstream (filename); in = new ObjectInputStream (FIS); p = (person) in.readobject (); In.close (); } catch (Exception ex) {ex.printstacktrace (); } System.out.println (P); }}
Java Object Serialization-tutorial