1:先创建一个对象类,设定一些属性
2:Serializable 接口的类是可序列化的。没有实现此接口的类将不能使它们的任意状态被序列化或逆序列化。
public class People implements Serializable {
private String name;
private int age;
private String sex;
private String address;
private String iphone;
//构造方法
public People() {
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", iphone='" + iphone + '\'' +
'}';
}
public People(String name, int age, String sex, String address, String iphone) {
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
this.iphone = iphone;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIphone() {
return iphone;
}
public void setIphone(String iphone) {
this.iphone = iphone;
}
}
3:序列化:是将对象的状态写入到特定的流中的过程
4:创建对象流:ObjectOutputStream(OutputStream out)
FileOutputStream fos = null;
FileInputStream fis = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("F:\\IdeaProjects\\Java-Api\\file\\object.txt");
oos = new ObjectOutputStream(fos);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
if (fis != null) {
fis.close();
}
if (oos != null) {
oos.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
5:准备需要序列化对象
people = new People("*", *, "*", "*", "123114131");
6:特有方法writeObject():输出可序列化的对象
oos.writeObject(people);
反序列化:则是从特定的流中获取数据重新构建对象的过程
7:创建对象流:ObjectInputStream(InputStream in)
fis = new FileInputStream("F:\\IdeaProjects\\Java-Api\\file\\object.txt");
ois = new ObjectInputStream(fis);
8:特有方法,readObject():读取对象,返回一个Object类型的对象,readObject()是没有参数的
People people1 = (People) ois.readObject();
System.out.println(people1.toString());