import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectStreamDemo {
public static void main(String[] args) {
/**
* 对象流
* ObjectOutputStream和ObjectInputStream类用于存储和读取基本类型数据或
* 对象的过滤流,他可以把java中的对象写到数据源中,也能把对象从数据源中还原回来。
* 用ObjectOutputStream类读取基本数据类型或对象的机制叫做序列化;ObjectInputStream
* 类读取数据类型或对象的机制叫做反序列化。ObjectOutputStream和ObjectInputStream不能序列化static和
* transient修饰的成员变量。
* 另外,能被序列化的对象所对应的类必须实现java.io.Serializable这个标志性接口。
*/
new ObjectStreamDemo().serializationTest("e:/pratice.html");
new ObjectStreamDemo().deserializationTest("e:/pratice.html");
/**
* 显式地定义serialVersionUID有一下两种用途:
* 1.在某些场合,希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有相同的serialVersionUID.
* 2.在某些场合,不希望类的不同版本对序列化兼容,因此需要确保类的不同版本具有不同的serialVersionUID.
*/
}
private void serializationTest(String filepath){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(filepath));
oos.writeObject(new Student(1, "xiex", 18));
oos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void deserializationTest(String filepath){
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filepath));
Student stu = (Student) ois.readObject();
System.out.println(stu);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private transient int age;
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}