序列化:把一个结构化数据(对象)编程一个二进制的bit流(就比如游戏中的存档,保存游戏场景) 反序列化:把二进制的bit流还原回原来的对象(就比如游戏中的读档)
序列化
代码语言:javascript复制import java.io.*;
class Student implements Serializable {
public String name;
public int age;
public int score;
}
public class IODemo6 {
public static void main(String[] args) throws IOException {
Student student = new Student();
student.name = "ss";
student.age = 12;
student.score = 34;
serialzeStudent(student);
}
private static void serialzeStudent(Student student) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("d:/student.txt"));
objectOutputStream.writeObject(student);//序列化和写文件同时搞定
objectOutputStream.close();
}
执行后会在指定位置生成一个student文件
反序列化
代码语言:javascript复制import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class IODemo7 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student ret = deserializeStudent();
System.out.println(ret.name);
System.out.println(ret.age);
System.out.println(ret.score);
}
public static Student deserializeStudent() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("d:/student.txt"));
Student s = (Student) objectInputStream.readObject();
return s;
}
}
就读取出了当前文件中的内容