对象流(ObjectOutputStream/ObjectInputStream)
增强了缓冲功能
增强了读写8种基本数据类型和字符串功能增强了读写对象的功能
1.readObject()从流中读取一个对象。
2.writeObject(Object obj)向流中写入一个对象。
构造方法:
ObjectOutputStream();
ObjectOutputStream( OutPutStream out );
ObjectInputStream( );
ObjectInputStream(InputStream in );
对象流序列化:
package com.tiedandan.IO流.对象流.序列化;
import java.io.*;
/**
* 执行序列化的类必须要实现 Serializable 接口
*/
public class ObjectIO {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("d:\\stu.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student stu = new Student("zhangsan",12);
//序列化(写入操作)
oos.writeObject(stu);
oos.close();
System.out.println("序列化完毕");
}
}
package com.tiedandan.IO流.对象流.序列化;
import java.io.Serializable;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
反序列化:
package com.tiedandan.IO流.对象流.反序列化;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectIO {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("d:\\stu.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
//读取对象,反序列化。
Student1 stu = (Student1) ois.readObject();//读操作只能执行一次。
ois.close();
System.out.println(stu.toString());
}
}
package com.tiedandan.IO流.对象流.反序列化;
import java.io.Serializable;
public class Student1 implements Serializable {
private String name;
private int age;
public Student1() {
}
public Student1(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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}