This article from JavaTuturial

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

    /**
* Write the specified object to the ObjectOutputStream. The class of the
* object, the signature of the class, and the values of the non-transient
* and non-static fields of the class and all of its supertypes are
* written. Default serialization for a class can be overridden using the
* writeObject and the readObject methods. Objects referenced by this
* object are written transitively so that a complete equivalent graph of
* objects can be reconstructed by an ObjectInputStream.
*
* <p>Exceptions are thrown for problems with the OutputStream and for
* classes that should not be serialized. All exceptions are fatal to the
* OutputStream, which is left in an indeterminate state, and it is up to
* the caller to ignore or recover the stream state.
*
* @throws InvalidClassException Something is wrong with a class used by
* serialization.
* @throws NotSerializableException Some object to be serialized does not
* implement the java.io.Serializable interface.
* @throws IOException Any exception thrown by the underlying
* OutputStream.
*/
public final void writeObject(Object obj) throws IOException {
if (enableOverride) {
writeObjectOverride(obj);
return;
}
try {
writeObject0(obj, false);
} catch (IOException ex) {
if (depth == 0) {
writeFatalException(ex);
}
throw ex;
}
}

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:

  /**
* Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overriden using the writeObject
* and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is
* reconstructed by readObject.
*
* <p>The root object is completely restored when all of its fields and the
* objects it references are completely restored. At this point the object
* validation callbacks are executed in order based on their registered
* priorities. The callbacks are registered by objects (in the readObject
* special methods) as they are individually restored.
*
* <p>Exceptions are thrown for problems with the InputStream and for
* classes that should not be deserialized. All exceptions are fatal to
* the InputStream and leave it in an indeterminate state; it is up to the
* caller to ignore or recover the stream state.
*
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
* @throws InvalidClassException Something is wrong with a class used by
* serialization.
* @throws StreamCorruptedException Control information in the
* stream is inconsistent.
* @throws OptionalDataException Primitive data was found in the
* stream instead of objects.
* @throws IOException Any of the usual Input/Output related exceptions.
*/
public final Object readObject()
throws IOException, ClassNotFoundException
{
if (enableOverride) {
return readObjectOverride();
} // if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:

class Employee implements java.io.Serializable{
public String name;
public String addr;
public transient int SSN;
public int num; public void mailCheck(){
System.out.println("Mailing a check to " + name + " " + addr);
}
}

Notice that for a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.

  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

    static void serializeEmployee(){
Employee e = new Employee();
e.name = "Reyan Ali";
e.addr = "Zpark, China";
e.SSN = 111222333;
e.num = 101; try{
FileOutputStream fileOut = new FileOutputStream("./employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i){
i.printStackTrace();
}
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

   static void deserializeEmployee(){
Employee e = null; try {
FileInputStream inputFile = new FileInputStream("./employee.ser");
ObjectInputStream in = new ObjectInputStream(inputFile);
e = (Employee) in.readObject();
in.close();
inputFile.close();
e.mailCheck(); } catch (IOException i){
i.printStackTrace();
} catch (ClassNotFoundException c){
c.printStackTrace();
}
}

Here are following important points to be noted:

  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

  • Notice that the return value of readObject() is cast to an Employee reference.

  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

The result and whole source code is here:

package serialization;

import java.io.*;

/**
* Created by *** on 1/3/16.
*/ class Employee implements java.io.Serializable{
public String name;
public String addr;
public transient int SSN;
public int num; public void mailCheck(){
System.out.println("Mailing a check to " + name + " " + addr);
}
} public class SerializeDemo { static void serializeEmployee(){
Employee e = new Employee();
e.name = "Reyan Ali";
e.addr = "Zpark, China";
e.SSN = 111222333;
e.num = 101; try{
FileOutputStream fileOut = new FileOutputStream("./employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i){
i.printStackTrace();
}
} static void deserializeEmployee(){
Employee e = null; try {
FileInputStream inputFile = new FileInputStream("./employee.ser");
ObjectInputStream in = new ObjectInputStream(inputFile);
e = (Employee) in.readObject();
in.close();
inputFile.close();
e.mailCheck(); } catch (IOException i){
i.printStackTrace();
} catch (ClassNotFoundException c){
c.printStackTrace();
}
} public static void main(String[] args){
serializeEmployee();
deserializeEmployee();
}
}

Output of console:

Serialized data is saved in employee.ser
Mailing a check to Reyan Ali Zpark, China

java Serialization and Deserializaton的更多相关文章

  1. The Java serialization algorithm revealed---reference

    Serialization is the process of saving an object's state to a sequence of bytes; deserialization is ...

  2. JAVA Serialization 序列化

    最近在做Android 项目时用到了WebView,可悲的是,在html上有无数用户的操作,而这些操作被JS返回给了Android的内存中,当深层的Activity开启时,之前的Activity很可能 ...

  3. JAVA-基础(六) Java.serialization 序列化

    序 列 化 序列化(serialization)是把一个对象的状态写入一个字节流的过程. Serializable接口 只有一个实现Serializable接口的对象可以被序列化工具存储和恢复.Ser ...

  4. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  5. Java transient关键字

    Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...

  6. java轻量级IOC框架Guice

    Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...

  7. Java内部类、静态嵌套类、局部内部类、匿名内部类

    Nested classes are further divided into two types: static nested classes: If the nested class is sta ...

  8. Java transient volatile关键字(转)

    Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...

  9. java volatile 和Transient 关键字

    java关键字volatile volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同 ...

随机推荐

  1. 调用父类Controller错误

    在写一个控制器的时候,要特别注意本类继承的父类.不要继承错了.如图: ,这样就会一直是显示父类的控制器,而不是显示本类的控制器视图. 应该改为: 这些都是平时遇到的一些小问题,留着提醒自己.

  2. 软件介绍:搜索工具 Listary

    如今的互联网时代,搜索的重要性我想大家都是认可的.网上的知识浩如烟海,而搜索引擎是通向这些知识的入口.谷歌.百度等搜索引擎给我们带来了极大的便利,也无怪他们成长为如今的互联网巨头. 然而储存在个人硬件 ...

  3. 交互设计师谈颠覆式创新 | Think different

    作者:Teambition 交互设计师 樊伟 本文由 Teambition 原创.转载请注明出处,附原文链接 题图:by Ed Chao 我们不需要像主流市场的大公司一样做类似相扑的庞大,而是需要像柔 ...

  4. Java程序在向mysql中插入数据的时候出现乱码

    今天在往数据库中插入数据的时候中文字符在数据库中就出现了乱码?网上有各种说法,但是适合我的,最终解决我的问题的只有下面一种! 在创建数据库的时候,注意设置编码方式. CREATE DATABASE ` ...

  5. Scala基础类型与操作

    Scala基本类型及操作.程序控制结构 Scala基本类型及操作.程序控制结构 (一)Scala语言优势 自身语言特点: 纯面向对象编程的语言 函数式编程语言 函数式编程语言语言应该支持以下特性: 高 ...

  6. 一句代码美化你的下框之jquery.selectMM修复版(jquery.selectMM v0.9 beta 20141217)

    一句代码美化你的下框之jquery.selectMM修复版(jquery.selectMM v0.9 beta 20141217) 浏览效果: http://www.beyond630.com/jqu ...

  7. python之单例设计模式

    设计模式之单例模式 单例设计模式是怎么来的?在面向对象的程序设计中,当业务并发量非常大时,那么就会出现重复创建相同的对象,每创建一个对象就会开辟一块内存空间,而这些对象其实是一模一样的,那么有没有办法 ...

  8. JavaScript 的 Promise

    先看这个 http://www.html5rocks.com/zh/tutorials/es6/promises/#toc-api  [JavaScript Promise 浏览器支持的Promise ...

  9. windows7下,protel 99se元件库加载问题的解决方案

    方法一:到C盘(系统盘),系统文件夹(c:\windows)下的ADVPCB99SE和ADVSch99SE文件先配置原理图,用本文打开ADVPCB99SE文件,在[Change Library Fil ...

  10. .NET(C#):XmlReader和Whitespace以及MoveToContent和ReadToFollowing方法

    原文 http://www.cnblogs.com/mgen/archive/2012/04/26/2471403.html XmlReader默认是读取XML文件中的Whitespace和注释的. ...