Java序列化
最近在学习java高级编程特性,今天学习了序列化与反序列化,总结了自己的学习笔记
序列化对象:
public final void writeObject(Object x) throws IOException
对象反序列化:
public final Object readObject() throws IOException, ClassNotFoundException
定义Employee类,该类实现了Serializable接口
import java.io.Serializable;
public class Employee implements Serializable {
public String name;
public String address;
//定义为transient的变量并不会被序列化
public transient int SSn;
public int number;
public void mailCheck(){
System.out.println("Mailing a check to" + name
+ " " + address);
}
}
请注意,一个类的对象要想序列化成功,必须满足两个条件:
1.该类必须实现 java.io.Serializable 对象。
2.该类的所有属性必须是可序列化的。如果有一个属性不是可序列化的,则该属性必须注明是短暂的。
如果你想知道一个 Java 标准类是否是可序列化的,请查看该类的文档。检验一个类的实例是否能序列化十分简单, 只需要查看该类有没有实现 java.io.Serializable接口。
序列化:
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "kafka zhou";
e.address = "Hadoop ecosphere";
e.SSn = 217;
e.number = 101;
try {
FileOutputStream fileOut = new FileOutputStream("C:/Users/Administrator.000/Desktop/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved ");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
反序列化:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("C:/Users/Administrator.000/Desktop/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSn);
System.out.println("Number: " + e.number);
em.mailcheck();
}
}