📄 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 + -