Java完成序列化與反序列化的簡略示例。本站提示廣大學習愛好者:(Java完成序列化與反序列化的簡略示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成序列化與反序列化的簡略示例正文
1.Java序列化與反序列化
Java序列化是指把Java對象轉換為字節序列的進程;而Java反序列化是指把字節序列恢復為Java對象的進程。
2.為何須要序列化與反序列化
我們曉得,當兩個過程停止長途通訊時,可以互相發送各類類型的數據,包含文本、圖片、音頻、視頻等, 而這些數據都邑以二進制序列的情勢在收集上傳送。那末當兩個Java過程停止通訊時,可否完成過程間的對象傳送呢?謎底是可以的。若何做到呢?這就須要Java序列化與反序列化了。換句話說,一方面,發送方須要把這個Java對象轉換為字節序列,然後在收集
傳送;另外一方面,吸收方須要從字節序列中恢復出Java對象。
當我們了了了為何須要Java序列化和反序列化後,我們很天然地會想Java序列化的利益。其利益一是完成了數據的耐久化,經由過程序列化可以把數據永遠地保留到硬盤上(平日寄存在文件裡),二是,應用序列化完成長途通訊,即在收集上傳送對象的字節序列。
3.示例:
(1)序列化反序列化文件:
import java.io.*; @SuppressWarnings("serial") class Person implements Serializable { public Person(String name, String sex, int age, int height) { this.name = name; this.sex = sex; this.age = age; this.height = height; } public String toString() { return "|" + this.name + "|" + this.sex + "|" + this.age + "|" + this.height + "|"; } public String name; public String sex; public int age; public int height; } public class SerialTest { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { Person p = new Person("Jim", "male", 28, 194); // 開端序列化 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( new File("myTest.txt"))); oos.writeObject(p); // 反序列化 ObjectInputStream ois = new ObjectInputStream(new FileInputStream( new File("myTest.txt"))); Person p1 = (Person) ois.readObject(); System.out.println(p1.toString()); } }
(2)XML反序列化成class:
import java.io.*; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; @SuppressWarnings("serial") class RoadInfo implements Serializable { public int id; public long MDN; public String NAME; public double LNG; public double LAT; public String ICON; } @SuppressWarnings("serial") class table_list implements Serializable { public String toString() { StringBuffer sb = new StringBuffer(); for (RoadInfo r : sequence) { sb.append("|"); sb.append(r.id); sb.append("|"); sb.append(r.MDN); sb.append("|"); sb.append(r.NAME); sb.append("|"); sb.append(r.LNG); sb.append("|"); sb.append(r.LAT); sb.append("|"); sb.append(r.ICON); sb.append("|\n"); } return sb.toString(); } public table_list(int count) { sequence = new RoadInfo[count]; for (int i = 0; i < count; i++) { sequence[i] = new RoadInfo(); } } public RoadInfo[] sequence; } public class XMLTest { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(new File( "friend_msg.xml"))); while (true) { String s = reader.readLine();// 讀一行 if (s == null) { break; } sb.append(s); } XStream xs = new XStream(new DomDriver()); table_list db = (table_list) xs.fromXML(sb.toString()); System.out.println(db.toString()); } }