学习Java这么久,虽然脑子中有关于序列化的理解,但没实际应用过,刚好碰到朋友要帮忙做个作业,就趁机写一个很简单的例子。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 对象的序列化主要有两种用途:
1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
2) 在网络上传送对象的字节序列。
*/
/**
* 要使对象序列化,就令该对象继承java.io.Serializable类。
*/
/**
* @author Jim
* @Time 2016年4月14日 下午1:47:48
*
*/
public class Program21 {
public static void main(String[] args){
try{
//序列化对象,将对象保存在student.dat中
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.dat"));
Student s1 = new Student("Lisa", 20);
out.writeObject(s1);//写入对象
out.close();
//将student.dat中的对象反序列化并print information.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.dat"));
Student s2 = (Student)in.readObject();//读出对象
System.out.print("Student's name is " + s2.getName() + " and the age is " + s2.getAge());
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 定义一个学生类来继承java.io.Serializable
*/
class Student implements Serializable {
private String name = "";
private int age = 0;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge() {
return this.age;
}
}