Student.java
**
* @Author:gaoyuan
* @Description:学生类
* @DateTime:2021/1/20 22:32
**/
public class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.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;
}
}
对象序列化流
ObjectOutputStreamDemo.java
/**
* @Author:gaoyuan
* @Description:对象序列化流
* @DateTime:2021/1/20 22:52
**/
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws IOException {
//创建一个写入指定的OutputStream的ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("code\\oos.txt"));
//创建对象
Student s = new Student("高富帅", 24);
//将指定的对象写入ObjectOutputStream
oos.writeObject(s);
//释放资源
oos.close();
}
}
如图所示乱码是正常的,因为序列化是基于二进制流的,把Student对象的信息以二进制存储在文本文件中,用文本编辑器打开自然是乱码。只有通过反序列话才能将存储的二进制读取出来,然后显示在控制台上。
反对象序列化流 ObjectInputStreamDemo.java
/**
* @Author:gaoyuan
* @Description:反对象序列化流
* @DateTime:2021/1/20 23:04
**/
public class ObjectInputStreamDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建从指定的InputStreamDemo读取的ObjectInputStreamDemo
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("code\\oos.txt"));
//ObjectInputStreamDemo读取一个对象
Object obj = ois.readObject();
Student s = (Student) obj;
System.out.println(s.getName() + "," + s.getAge());
ois.close();
}
}
输出;