IO流第37天(ObjectInputStream反序列化,标准输入输出流)
ObjectInputStream反序列化(此处遇到问题,已解决)
案例:使用ObjectInputStream将date反序列化
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建反序列化的文件
String filePath = "d:\\date.dat";
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(filePath));
//读取(反序列化)的顺序需要和保存数据(反序列化)的顺序一致
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.readChar());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
// Object dog=ois.readObject();
// System.out.println(dog);
ois.close();
}
错误:序列化和反序列化的结果不一致(该错误是由于反序列化的读取方式不一样导致)

注意:
1,如果想要调用Dog的方法,就需要向下转型
2,需要将Dog的定义放到可以引用的位置
对象处理流使用细节
- 读取顺序要一致
![image]()
![image]()
- 要求实现序列化和反序列化的对象要实现Serializable接口
![image]()
- 序列化的类中建议添加SerialVersionUID
- 序列化对象时,默认将里面所有的属性都进行序列化,但是除了static和transient修饰的成员(不会报错,但是也不会被序列化和反序列化)
- 序列化对象时,要求里面属性的类型也需要实现序列化接口
- 序列化具有可继承性,如果某类实现了序列化接口,那么它的子类也默认实现了序列化接口
标准输入输出流
| 类型 | 默认设备 | |
|---|---|---|
| System.in标准输入 | InputStream | 键盘 |
| System.out标准输出 | PrintStream | 显示器 |
| System.in:编译类型:InputStream,运行类型:BufferedInputStream | ||
| System.out:编译类型和运行类型都是PrintStream |
//System类的 public static final InputStream in = null;
//编译类型:InputStream
//运行类型:BufferedInputStream
System.out.println(System.in.getClass());
//System.out类的 public static final PrintStream out = null;
//编译类型和运行类型都是PrintStream
System.out.println(System.out.getClass());
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
String str= scanner.next();
System.out.println(str);




浙公网安备 33010602011771号