基础知识:
1.Java序列化是将对象转换成字节序列的过程;反之,反序列化就是将字节序列转换成原来的类对象的过程。
2.判断Java类对象是否可序列化,只需判断需序列化的类是否阶成了java接口java.io.Serializable,只有当类继承了该接口,该类的对象才可被序列化。
3.序列化中使用的API:java.io.ObjectOutputStream和java.io.ObjectInputStream。
序列化和反序列化实例:
Employee类,用于实例化将被序列化的对象
package com.anson.java;
/**
* Employee类使用
* @author anson
*
*/
public class Employee implements java.io.Serializable {
private String Name;
private int Age;
private String Address;
public Employee()
{
}
/**
* 构造
* @param Name
* @param Age
* @param Address
*/
public Employee(String Name,int Age,String Address)
{
this.Name=Name;
this.Age=Age;
this.Address=Address;
}
/**
* 输出参数
* @return
*/
public String Name()
{
return this.Name;
}
public int Age()
{
return this.Age;
}
public String Address()
{
return this.Address;
}
}
SerObj类是静态内部类,用于测试序列化及反序列化
package com.anson.java;
import java.io.*;
import java.util.Vector;
/**
* 序列化Employee对象
* @author anson
*
*/
public class SerObj {
/**
* 序列化
* @param obj
* @param path
*/
public static void SerObject(Object obj,String path)
{
try
{
File file=new File(path);
FileOutputStream outStream=new FileOutputStream(file);
ObjectOutputStream ObjStream = new ObjectOutputStream(outStream);
for(int i=0;i<10;i++)
{
Employee e=new Employee("Name"+i,10+i,"Address"+i);
ObjStream.writeObject(e);
}
ObjStream.close();
outStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 反序列化
* @param path
*/
public static void UnSerObject(String path)
{
try
{
File file = new File(path);
FileInputStream InputStream=new FileInputStream(file);
ObjectInputStream ObjStream=new ObjectInputStream(InputStream);
Vector<Employee> vec=new Vector<Employee>();
for(int i=0;i<10;i++)
{
vec.add((Employee)ObjStream.readObject());
}
ObjStream.close();
InputStream.close();
for(int i=0;i<vec.size();i++)
{
System.out.print(vec.get(i).Name()+" ");
System.out.print(vec.get(i).Age()+" ");
System.out.println(vec.get(i).Address());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Test类
package com.anson.java;
/**
* java序列化测试
* @author anson
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SerObj.SerObject(null, "/home/anson/桌面/Infor.ser");
SerObj.UnSerObject("/home/anson/桌面/Infor.ser");
}
}
测试结果:
运行后将生成文件,用于保存被序列化的对象,独处文件部分结果如下