/**
* 对象序列化
*/
class Person implements Serializable { //标记被序列化的对象
private String name;
private int age;
public Person(String name,int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name +",age=" + age + "]";
}
}
class TestDemo {
//设定一个存放二进制的文件地址
public static final File FILE = new File("E:" + File.separator + "aaa" + File.separator + "a.txt");
public static void main(String[] args) throws IOException, ClassNotFoundException {
ser(new Person("张三",19)); //实例化被标记的对象
dser();
}
//序列化操作
public static void ser(Object obj) throws FileNotFoundException, IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE)); //指定存放二进制地址
oos.writeObject(obj); //把序列化的obj写入ObjectOutputStream中
oos.close();
}
//反序列化操作
public static void dser() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE)); //获取被序列化的文件
System.out.println(ois.readObject()); //读取二进制数据转换成原始数据并输出
ois.close();
}
}
* 对象序列化
*/
class Person implements Serializable { //标记被序列化的对象
private String name;
private int age;
public Person(String name,int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name +",age=" + age + "]";
}
}
class TestDemo {
//设定一个存放二进制的文件地址
public static final File FILE = new File("E:" + File.separator + "aaa" + File.separator + "a.txt");
public static void main(String[] args) throws IOException, ClassNotFoundException {
ser(new Person("张三",19)); //实例化被标记的对象
dser();
}
//序列化操作
public static void ser(Object obj) throws FileNotFoundException, IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE)); //指定存放二进制地址
oos.writeObject(obj); //把序列化的obj写入ObjectOutputStream中
oos.close();
}
//反序列化操作
public static void dser() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE)); //获取被序列化的文件
System.out.println(ois.readObject()); //读取二进制数据转换成原始数据并输出
ois.close();
}
}