Person类
public class Person implements Serializable {
static final long serialVersionUID = 10086L;
private String name ;
public Integer age;
// constructor
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Method
// Person ArrayList<Person> Serializable and UnSerializable
// 存储person类的集合(ArrayList<Person>)的序列化和反序列化
// ArrayList<Person> Serializable
// 以下为 ArrayList<Person> 对象的序列化
public static void method_Serializable() throws IOException {
// Create byte output stream
// 创建字节输出流
FileOutputStream fileOutputStream = new FileOutputStream("E:\\folder_io_dome\\domeDir03\\Person_1.object");
// create object output stream
// 创建对象输出流
ObjectOutputStream obj = new ObjectOutputStream(fileOutputStream);
// create array_list
ArrayList<Person> person_array_list = new ArrayList<>();
// add object
person_array_list.add(new Person("yuanhao_01", 18));
person_array_list.add(new Person("yuanhao_02", 18));
person_array_list.add(new Person("yuanhao_03", 18));
person_array_list.add(new Person("yuanhao_04", 18));
// show name
for (int i = 0; i < person_array_list.size(); i++) {
System.out.println(person_array_list.get(i).getName());
}
// will object write disk
// Serializable ArrayList<Person> on the disk
// 将对象序列化至硬盘
obj.writeObject(person_array_list);
// close stream
// 关闭流
obj.flush();
obj.close();
fileOutputStream.close();
}
// ArrayList<Person> UnSerializable
// 以下为 ArrayList<Person> 对象的反序列化
public static void method_UnSerializable() throws IOException, ClassNotFoundException {
// create byte input stream
// 创建字节输入流
FileInputStream fileInputStream = new FileInputStream("E:\\folder_io_dome\\domeDir03\\Person_1.object");
// create object input stream
// 创建对象输入流
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
// UnSerializable Object
Object obj = objectInputStream.readObject();
// create ArrayList_object , accept object
// 创建ArrayList对象,接受obj对象
ArrayList<Person> arrayList_person = null;
// flag obj isCast ArrayList_object
// 判断object是否可以转换为ArrayList
if (obj instanceof ArrayList) arrayList_person = (ArrayList)obj;
Person p = null;
// flag , element on the 'arrayList_person' cast to Person
// 判断,arrayList_person中的元素,是否可以转换为Person对象
if (arrayList_person.get(0) instanceof Person){
for (int i = 0; i < arrayList_person.size(); i++) {
p = arrayList_person.get(i);
System.out.println("Name is : " + p.getName() + " Age is :" + p.getAge());
}
}else {
// output show
System.out.println("Element on the arrayList , not is person object");
}
objectInputStream.close();
fileInputStream.close();
}