The classes ObjectInputStream and ObjectOutputStream support reading and writing Java objects that you use in the program.
The process of converting objects into sequence of bytes is known as serialization.
The mechanism of storing objects in memory into files is known as persistence.
ObjectStreamExample.java
package com.appfworks.io;
/**
* Created by suresh on 31/10/15.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
// A simple class to illustrate object streams: fill a data structure, write it to a
// temporary file and read it back and print the read data structure
class ObjectStreamExample {
public static void main(String []args) {
MappresidentsOfUS = new HashMap<>();
presidentsOfUS.put("Barack Obama", "2009 to --, Democratic Party, 56th term");
presidentsOfUS.put("George W. Bush", "2001 to 2009, Republican Party, 54th and 55th terms");
presidentsOfUS.put("Bill Clinton", "1993 to 2001, Democratic Party, 52nd and 53rd terms");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.data"))) {
oos.writeObject(presidentsOfUS);
} catch(FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name ");
} catch(IOException ioe) {
System.err.println("an I/O error occurred while processing the file");
} // the ObjectOutputStream will auto-close, so don't have to worry about it
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.data"))) {
Object obj = ois.readObject();
// first check if obj is of type Map
if(obj != null && obj instanceof Map) {
Mappresidents = (Map ) obj;
System.out.println("President name \t Description \n");
for(Map.Entrypresident : presidents.entrySet()) {
System.out.printf("%s \t %s %n", president.getKey(),
president.getValue());
}
}
} catch(FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name ");
} catch(IOException ioe) {
System.err.println("an I/O error occurred while processing the file");
} catch(ClassNotFoundException cnfe) {
System.err.println("cannot recognize the class of the object - is the file corrupted?");
}
}
}
You need to implement the Serializable interface in a class if you want to make the objects of the class serializable.
You can declare a member variable as transient and that variable will not be serialized by the JVM.
TransientSerialization.java
package com.appfworks.io;
/**
* Created by suresh on 31/10/15.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class USPresident implements Serializable {
private static final long serialVersionUID = 1L;
@Override
public String toString() {
return "US President [name=" + name + ", period=" + period + ", term=" + term + "]";
}
public USPresident(String name, String period, String term) {
this.name = name;
this.period = period;
this.term = term;
}
private String name;
private String period;
private transient String term;
}
class TransientSerialization {
public static void main(String[] args) {
USPresident usPresident = new USPresident("Barack Obama", "2009 to --", "56th term");
System.out.println(usPresident);
//Serialize the object
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("USPresident.data"))) {
oos.writeObject(usPresident);
} catch (FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name ");
} catch (IOException ioe) {
System.err.println("an I/O error occurred while processing the file");
} // the ObjectOutputStream will auto-close, so don't have to worry about it
//De-serialize the object
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("USPresident.data"))) {
Object obj = ois.readObject();
if (obj != null && obj instanceof USPresident) {
USPresident presidentOfUS = (USPresident) obj;
System.out.println(presidentOfUS);
}
} catch (FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name ");
} catch (IOException ioe) {
System.err.println("an I/O error occurred while processing the file");
} catch (ClassNotFoundException cnfe) {
System.err.println("cannot recognize the class of the object - is the file corrupted ? ");
}
}
}
What you can observe from the output is that the value of the field term is not stored by the program. Why? Because you declared term as a transient field. All class members declared as transient are not serialized, so their values are lost after deserialization.
serialVersionUID
If you are implementing Serializable and not defining serialVersionUID, you will get a warning message.
if you don’t define it, JVM will define it for you; JVM will compute it based on the class behavior.
why it is required?
- It is there to prevent mistakenly loading a wrong version of a class while deserializing.
- defining serialVersionUID enables the serialized program to work across different JVM implementations seamlessly.
- whenever you make a change in a serialized class, do not forget to change the serialVersionUID also.
No comments:
Post a Comment