标签:turn super 接口 pack this txt 关闭 cep name
写对象:序列化,对象的状态以字节的形式储存
读对象:反序列化,磁盘上的字节形式的数据还原成对象的内存状态
只有实现了serializable接口才可以被序列化
package com.study02;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class a04 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
write();
read();
}
public static void read() throws FileNotFoundException, IOException, ClassNotFoundException {
//创建流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("g.txt"));
//写对象
System.out.println(ois.readObject());
//关闭
ois.close();
}
public static void write() throws FileNotFoundException, IOException {
//创建对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("g.txt"));
//写对象
oos.writeObject(new person("陆俊龙",20));
//关闭
if (oos!=null) {
oos.close();
}
}
}
package com.study02;
import java.io.Serializable;
public class person implements Serializable{
private String name;
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 person(String name, int age) {
super();
this.name = name;
this.age = age;
}
private int age;
@Override
public String toString() {
return name;
}
}
标签:turn super 接口 pack this txt 关闭 cep name
原文地址:https://www.cnblogs.com/LuJunlong/p/11831182.html