標籤:java序列化
學習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;}}
本文出自 “A&D_Ro535” 部落格,請務必保留此出處http://ro535.blog.51cto.com/11279790/1763771
Java序列化的一個例子