1.自定义Person类(序列化的要求见代码)
/*
person需要满足如下的要求,方可序列化
1.需要实现接口:Serialiable
2.当前类提供一个全局常量:serialVersionUID
3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的
4.ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
*/
public class Person implements Serializable {
public static final long serialVersionUID=24324234L;
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", 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;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
2.序列化操作
/*
对象流的使用
1.objectinputstream和objectoutputstream
2.作用:用于存储和读取基本数据类型数据或对象的处理流。他的强大之处就是可以把java中的对象写入到数据源中。也能把对象从数据源中还原回来
3.要想一个java对象是可序列化的,需要满足相应的要求,见Person类
*/
public class ObjectInputOutputStream {
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutPutStream实现
*/
@Test
public void test(){
ObjectOutputStream oos=null;
try {
//1.
oos=new ObjectOutputStream(new FileOutputStream(new File("object.bat")));
//2.
//oos.writeObject(new String("我爱北京天安门"));
//oos.flush();//刷新操作
oos.writeObject(new Person("Tom",23));//添加person数据
oos.flush();//刷新操作
}
catch (IOException e){
e.printStackTrace();
}
finally {
if(oos!=null)
try {
//3.
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
/*
反序列化:将磁盘文件中的对象还原为内存中的一个Java对象
使用ObjectInputStream
*/
public void test1(){
ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream(new File("object.bat")));
//Object o = ois.readObject();
//String str=(String) o;
//System.out.println(str);
Object o1 = ois.readObject();
Person p=(Person) o1;
System.out.println(p);
}
catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}
finally {
if (ois!=null)
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}