Java对象流与序列化

Java语言支持一种称为对象序列化(object serialization)的非常通用的机制,它可以将任何对象写入到流中,并在之后将其读回。被序列化的每个对象都有一个序列号,唯一标识该对象,而不是通过该对象的内存地址来表示对象。这样就能将一个对象集合从一台集群传送到另一台机器,与对象在内存中的地址无关。

示例:

ObjectStreamTest.java

import java.io.*;
/**
* Created by lbd on 2017/1/5.
*/
public class ObjectStreamTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
carl.setSecretary(harry);
Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
tony.setSecretary(harry);
Employee[] staff = new Employee[3];
staff[0] = carl;
staff[1] = harry;
staff[2] = tony;
try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee1.dat"))){
out.writeObject(staff);
}
try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee1.dat"))){
Employee[] newStaff = (Employee[]) in.readObject();
for (Employee e : newStaff){
System.out.println(e);
}
}
}
}
class Employee implements Serializable{
String name;
double salary;
int year;
int month;
int day;
public Employee(String name,double salary,int year,int month,int day){
this.name = name;
this.salary = salary;
this.year = year;
this.month = month;
this.day = day;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
@Override
public String toString() {
return this.name + " " + this.salary + " " + this.year + " " + this.month + " " + this.day;
}
}
class Manager extends Employee implements Serializable{
Employee secretary;
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
}
public void setSecretary(Employee e){
this.secretary = e;
}
}

注意:

  • Employee和Manager都必须实现Serializable接口才能被序列化!(Serializable接口没有任何方法)
  • 对象流输出中包含所有对象的类型和数据域
  • 每个对象都被赋予一个序列号
  • 相同对象的重复出现将被存储为对这个对象的序列号的引用

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :