对象序列化
作用
以内存为基础,吧内存中的额对象存储到磁盘文件中去,称为对象的序列化,防止程序反复调用文件造成浪费
ObjectOutputStream(字节对象输出流)
构造器
public ObjectOutputStream(Outputstream out):把低级字节输出流包装成高级的对象字节输出流
方法
public final void writeObject(Object obj):把对象写出去到对象序列化流的文件中去
代码的实现
Student.java
package work;
public class Student {
private String name;
private String sno;
public Student() {
}
public Student(String name, String sno) {
this.name = name;
this.sno = sno;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sno='" + sno + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
}
example.java
package work;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class example {
public static void main(String[] args) {
try (
ObjectOutputStream objectOutputStream = new ObjectOutputStream (new FileOutputStream ("D:\\Users\\cczyan\\Desktop\\JavaStudy\\txt01.txt"))
) {
Student student = new Student ("测试", "1931613077");
objectOutputStream.writeObject (student);
} catch (Exception e) {
e.printStackTrace ();
}
}
}
运行结果
会报错,未序列化异常,因为我们代码在进行序列化的时候,需要在实体类Student中继承Serializable序列化接口,因为对象存在文件中需要有“规矩”,这个“规矩”格式需要由java规定因此我们要继承Serializable接口
对象反序列化
作用
以内存为基础,把存储到磁盘文件中去的对象数据恢复成内存中的对象,称为对象的反序列化
ObjectInputStream(对象字节输入流)
构造器
public ObjectInputStream(InputStream out):把低级字节输入流包装成高级的对象字节输入流
反序列化方法
public Object readObject():把存储到磁盘文件中去的对象数据恢复成内存中的对象返回
代码实现
try (
ObjectInputStream inputStream = new ObjectInputStream (new FileInputStream ("D:\\Users\\cczyan\\Desktop\\JavaStudy\\txt01.txt"))
) {
Student student = (Student) inputStream.readObject ();
System.out.println (student);
} catch (Exception e) {
e.printStackTrace ();
}
注意:如果我们不想该变量被序列化时,我们可以在实体类的该变量前面添加transient来表示该变量不需要进行序列化,这样如果别人拿到这个文件也不会获取到该变量的信息
实例
try (
ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream ("D:\\Users\\cczyan\\Desktop\\JavaStudy\\txt01.txt"));
ObjectInputStream inputStream = new ObjectInputStream (new FileInputStream ("D:\\Users\\cczyan\\Desktop\\JavaStudy\\txt01.txt"))
) {
Student student1 = new Student ("测试中", "2022231863");
outputStream.writeObject (student1);
Student student = (Student) inputStream.readObject ();
System.out.println (student);
} catch (Exception e) {
e.printStackTrace ();
}