与数据流相同:处理基本数据类型和字符串
与数据流不同:处理其他各种对象(包括)
特殊概念: 序列化和反序列化原则:
1、先写出后读取
2、读取的顺序和写出的一致
3、不是所有的对象都可以序列化
自定义的对象需要序列化需要实现Serialization接口(虚拟机识别的“通行证”)
ObjectOutputStream: Object -(输出)-> Stream of byte(Serialization序列化) -(存储)-> file/DB/memory
ObjectInputStream: Object <-(输入)- Stream of byte(Deserialization反序列化) <-- file/DB/memory
void | writeObject(Object obj) | 将指定的对象写入 ObjectOutputStream |
Object | readObject() | 从 ObjectInputStream 读取对象 |
测试代码:
public class ObjectTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// ①写出
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
// 操作数据类型+数据
oos.writeUTF("凡是过往");
oos.writeInt(18);
oos.writeChar('a');
oos.writeBoolean(false);
// 对象(字符串、日期、自定义的对象(手动实现序列化))
oos.writeObject("皆为序列");/*字符串实现了序列化:public class String implements java.io.Serializable*/
oos.writeObject(new Date());/*日期实现了序列化:public class Date implements java.io.Serializable*/
Employee emp = new Employee("John",1024);/*Employee手动实现了序列化:class Employee implements java.io.Serializable*/
oos.writeObject(emp);
oos.flush();
byte[] datas = baos.toByteArray();
System.out.println(datas.length);
// ②读取
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
String msg = ois.readUTF();
int age = ois.readInt();
char grade = ois.readChar();
boolean flag = ois.readBoolean();
Object str = ois.readObject();
Object date = ois.readObject();
Object emploee = ois.readObject();
// 把各种类型的转化成字符串instanceof
/*是String实例,则将其转化成字符串*/
if(str instanceof String) {
String strObj = (String)str;
System.out.println(strObj);
}
if(date instanceof Date) {
Date dateObj = (Date)date;
System.out.println(dateObj);
}
if(emploee instanceof Employee) {
Employee emploeeObj = (Employee)emploee;
System.out.println(emploeeObj.getName() + "-->" + emploeeObj.getSalary());
}
}
}
//Javabean用于封装数据
class Employee implements java.io.Serializable{
private String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
测试结果:
172
皆为序列
Thu Sep 05 17:19:13 CST 2019
John-->1024.0