在上一篇文章中我简单的介绍了io类中的高级流缓冲流,具体继续来介绍一个高级流——对象流
新建一个对象
public class Person implements Serializable {
private String name;
private int age;
private String gender;
private transient String[] otherInfo;
public Person(String name, int age, String gender, String[] otherInfo) {
this.name = name;
this.age = age;
this.gender = gender;
this.otherInfo = otherInfo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", otherInfo=" + Arrays.toString(otherInfo) +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String[] getOtherInfo() {
return otherInfo;
}
public void setOtherInfo(String[] otherInfo) {
this.otherInfo = otherInfo;
}
}
对象流的序列化
对象流
java.io.ObjectOutputStream和ObjectInputStream
对象流是一对高级流,在流连接中的作用是进行对象的序列化与反序列化
对象序列化:将一个java对象转换为一组可以被保存或传输的字节的过程
String name = "张三";
int age = 18;
String gender = "男";
String[] otherInfo = {"高", "富", "帅"};
Person p = new Person(name, age, gender, otherInfo);
FileOutputStream fos = new FileOutputStream("person.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.close();
对象的反序列化
FileInputStream fis = new FileInputStream("person.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Person p = (Person) ois.readObject();
System.out.println(p);
ois.close();