?? objectserialtest.java
字號:
package io;
/*當一個對象被序列化時,只保存對象的非靜態成員變量,不能保存任何的成員方法和靜態的成員變量。
如果一個對象的成員變量是一個對象,那么這個對象的數據成員也會被保存。
如果一個可序列化的對象包含對某個不可序列化的對象的引用,那么整個序列化操作將會失敗,
并且會拋出一個NotSerializableException。我們可以將這個引用標記為transient,
那么對象仍然可以序列化。
對象輸出流ObjectOutputStream和對象輸入流ObjectInputStream分別實現了DataOutput和DataInput接口,
所以它們能讀取基本的數據類型.
*/
import java.io.*;
public class ObjectSerialTest {
public static void main(String[] args) throws Exception{
Employee e1=new Employee("zhangsan",24,6000);
Employee e2=new Employee("lishi",26,7500.50);
Employee e3=new Employee("zhangsan",2,6000);
FileOutputStream fos=new FileOutputStream("employee.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(e1);//將對象寫入對象流中.這是序列化過程.
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();
FileInputStream fis=new FileInputStream("employee.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Employee e;
for(int i=0;i<3;i++){
e=(Employee)ois.readObject();//readObject()返回的是一個Object對象,
//因此要強制類型轉換.這是反序列化過程.
System.out.println(e.name+" : "+e.age+" : "+e.salary);
}
}
}
class Employee implements Serializable{
String name;
int age;
double salary;
transient Thread t=new Thread();//線程對象不可序列化,因此將其標識為transient使其不參與序列化.
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -