序列化
Java在运行时,如果需要保存对象的状态(下次程序再运行时,也能还原当前对象的状态),就需要使用到序列化操做,本质就是把对象保存为磁盘上,下次运行时从磁盘上读取文件,恢复对象(反序列化)
举例:Student对象,在运行时给姓名赋值为张三,年龄赋值为20岁,这个对象在程序运行结束就消失了,下次程序运行时又要重新创建对象并赋值,要想下一次运行的时候对象还在,这种情况就需要使用序列化
网络程序,如果想把一个对象从一台机器发送到另一台机器(虚拟机),这种情况也需要把对象序列化为二进制内容,然后再网络发送,对方收到二进制内容,再反序列化为对象
ObjectOutputStream序列化
把正在运行的对象保存为文件
要被序列化的对象的类要实现Serializable接口
- Student类实现接口Serializable
package com.hqyj;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
/**
* set方法,参数
*
* get方法,输出的内容
*
* @return
*/
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 Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"姓名:'" + name + '\'' +
", 年龄:" + age +
'}';
}
}
-
SerlizeableDemo序列化类
利用 objectOutputStream类的writeObject方法做序列化
package com.hqyj;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerlizeableDemo {
public static void main(String[] args) {
/**
* 序列化
*/
Student student = new Student("张三",22);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("E:\\Desktop\\备用.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(student);//序列化student对象
objectOutputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (objectOutputStream != null)
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ObjectInpputStream反序列化类
利用 objectInputStream类的readObject方法做序列化
package com.hqyj;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerlizeableDemo {
/**
* 反序列化
* @param args
*/
public static void main(String[] args) {
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = new FileInputStream("E:\\Desktop\\备用.txt");
objectInputStream = new ObjectInputStream(fileInputStream);
//读取以前序列化的文件,还原为原来的对象,还原后对象的属性都还在
Student student = (Student) objectInputStream.readObject();
System.out.println(student);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
if (objectInputStream != null){
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}