Java中IO序列化和反序列化的注意事項:
阿新 • • 發佈:2020-12-16
序列化和反序列化的注意事項:
/*
* 使用ObjectOutputStream實現物件的序列化
* 注意事項:
* 1.序列化的類必須要實現Serializable介面
* 2.序列化類中物件屬性要求實現Serializzable介面
* 3.序列化版本號ID,保證序列化的類和反序列化的類是同一個類
* 4.使用transient(瞬間的)修飾屬性,這個屬性不能序列化
* 5.靜態屬性不能被序列化
* 6. 序列化多個物件
* */
public class TestObjectOutputStream {
public static void main (String[] args) throws Exception {
//1.建立物件流
FileOutputStream fos=new FileOutputStream("f:\\IO\\zhangsan.jpg");
ObjectOutputStream oos=new ObjectOutputStream(fos);
//2.序列化
Student zhangsan=new Student("張三",101);
Student lisi=new Student ("李四",102);
ArrayList<Student> arr=new ArrayList<Student>();
arr.add(zhangsan);
arr.add(lisi);
oos.writeObject(arr);
//關閉
oos.close();
System.out.println("序列化完畢");
}
}
/*
* 使用OBjectInputStream 實現反序列化(讀取重構成物件)
* */
public class TestObjectInputStream {
public static void main(String[] args) throws Exception{
//1.建立物件流
FileInputStream fis=new FileInputStream("f:\\IO\\zhangsan.jpg");
ObjectInputStream ois=new ObjectInputStream(fis);
//2.讀取檔案
// Student s=(Student)ois.readObject();
// Student s1=(Student)ois.readObject();
ArrayList<Student> list=(ArrayList<Student>) ois.readObject();
//關閉流
ois.close();
System.out.println("反序列化完畢");
// System.out.println(s.toString());
// System.out.println(s1.toString());
System.out.println(list.toString());
}
}
//如果Student不實現 Serializable介面 則序列化報錯
public class Student implements Serializable {
private static final long serialVersionUID=111L;
private String name;
private transient int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}