对象流 ObjectInputStream和ObjectOutputStream
- 序列化: 保存数据时,保存数据的值和数据类型
- 反序列化: 恢复数据时,恢复数据的值和数据类型
- 为了让某个类是可序列化的,需要让类实现以下两个接口之一:
- Serializable //这是一个标记接口,声明性质,没有方法,推荐
- Externalizable //该接口有方法,需要实现
ObjectOutputStream(序列化)
- 继承变量使用ObjectOutputStream自带方法,自动实现Serializable接口,write和writeInt有很大区别
- 继承Object对象时,对象需要继承Serializable接口
- 无法序列化static修饰的静态成员
public static void main(String[] args) throws IOException {
String filePath = "C:\\Users\\Laity\\Desktop\\Java全栈\\JavaIO\\Test文件\\ja.wjs";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
oos.writeInt(100);
oos.writeChar('a');
oos.writeUTF("方法自动实现接口");
oos.writeObject(new dog("wjs",12));
oos.close();
System.out.println("save success....");
}
class dog implements Serializable {
String name;
int age;
public dog(String name, int age) {
this.name = name;
this.age = age;
}
}
ObjectOutputStream(反序列化)
- 读取的顺序要和你保存数据(序列化)的顺序一致,否则会异常
- getclass是获取对象的类名
public static void read() throws IOException, ClassNotFoundException {
String filePath = "C:\\Users\\Laity\\Desktop\\Java全栈\\JavaIO\\Test文件\\ja.wjs";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
System.out.println(ois.readInt());
System.out.println(ois.readChar());
System.out.println(ois.readUTF());
Object obj = ois.readObject();
System.out.println(obj.getClass());
dog dog01 = (dog) obj;
System.out.println(dog01.name);
System.out.println("\nread success...");
ois.close();
}