一、對象流:ObjectInputStream、 ObjectOutputStream
二、作用: 用於存儲和讀取基本數據類型或者對象的處理流
三、序列化機制:將在內存層面的Java對象保存在磁盤層面或者用網絡進行傳輸,使用ObjectOutputStream實現
四、反序列化機制:將在磁盤層面的對象還原成內存層面的Java對象,使用ObjectInputStream來實現
五、自定義類實現序列化要求:
-
1.需要實現接口:Serializable
-
2.當前類提供一個全局常量:serialVersionUID
-
3.除了當前Person類需要實現Serializable接口之外。還需要保證其內部所有屬性必須也是可序列化的 (默認情況下,基本數據類型都是可序列化的)
-
4.補充:ObjectOutputStream和ObjectInputStream不能去序列化static和transient修飾的成員變量
-
(static爲類所有的,不歸對象所有,transient表示,就是不想序列化)
public class ObjectInputOutputTest {
@Test
public void test1(){
//1
ObjectOutputStream oos = null;
try {
File file = new File("D:\\360MoveData\\Users\\Administrator\\Desktop\\亂七八糟\\文件\\Day02\\ObjectStream\\object.dat");
oos = new ObjectOutputStream(new FileOutputStream(file));
//2
oos.writeObject(new String("我是彭于晏!"));
oos.flush(); //刷新一下
oos.writeObject(new Person("lxx",21));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos!=null){
//3
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 反序列化:將磁盤文件中的對象還原成內存方面的一個Java對象
*使用ObjectInputStream來實現
* */
@Test
public void test2(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(new File("D:\\360MoveData\\Users\\Administrator\\Desktop\\亂七八糟\\文件\\Day02\\ObjectStream\\object.dat")));
Object o = ois.readObject();
String str=(String) o;
Object o2=ois.readObject();
Person p= (Person) o2;
System.out.println(str);
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
六、自定義序列化類
import java.io.Serializable;
public class Person implements Serializable {
String name;
int age;
public static final long serialVersionUID = 1234L;
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}