Java基础知识➣序列化与反序列化(四)

2023-04-24,,

概述

  Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。

  将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。

序列化所需类

  类 ObjectInputStream 和 ObjectOutputStream 是高层次的数据流,它们包含序列化和反序列化对象的方法。ObjectOutPutStream进行对象的序列化成二进制或者字符串,其中主要使用的方法是writeObject(object data);ObjectInputStream是将二进制或者字符串反序列化成对象,主要采用的方法是readObject()

  类需要序列化必须实现 java.io.Serializable 对象。与序列化对应关键字transient

序列化代码块

  将对象化对象保存到流中,将流里面的数据进行Base64编码。主要用到类FileOutPutStream和FileInputStream、ByteArrayOutputStream和ByteArrayInputStream。对象的使用如实例代码:

public class SerializeDemo {
public static void SeriaData()
{
Employee em=new Employee();
em.name="Justin";
em.address="GD China Num 98";
em.SSN=;
em.number=;
try{ // FileOutputStream fileout=new FileOutputStream("c:/employee.ser");
// ObjectOutputStream out=new ObjectOutputStream(fileout);
// out.writeObject(em);
// out.close();
// System.out.printf("Serialized data is saved in c:/employee.ser"); ByteArrayOutputStream outstring=new ByteArrayOutputStream();
ObjectOutputStream out=new ObjectOutputStream(outstring);
out.writeObject(em);
out.close();
String photodata = Base64.getEncoder().encodeToString(outstring.toByteArray());
System.out.println(photodata); Employee nem=new Employee();
ByteArrayInputStream strim=new ByteArrayInputStream(Base64.getDecoder().decode(photodata));
ObjectInputStream svtin=new ObjectInputStream(strim);
nem=(Employee)svtin.readObject();
strim.close();
nem.maillCheck(); // FileInputStream fileIn = new FileInputStream("c:/employee.ser");
// ObjectInputStream in = new ObjectInputStream(fileIn);
// nem = (Employee) in.readObject();
// in.close();
// fileIn.close();
// nem.maillCheck();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
} class Employee implements Serializable
{
public String name;
public String address;
public transient int SSN;
public int number; public void maillCheck()
{
System.out.println("Mailing a check to "+name +" Address:"+address);
} }

Java基础知识➣序列化与反序列化(四)的相关教程结束。

《Java基础知识➣序列化与反序列化(四).doc》

下载本文的Word格式文档,以方便收藏与打印。