时间:2023-02-13 10:22:28 | 栏目: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()); } }