package com.neusoft.test1; //首先定义一个被序列化的类
import java.io.Serializable;
class Student implements Serializable {// 定义一个可以被序列化的类
String name;
int age;
String num;
double score;
public Student() {
}
public Student(String name, int age, String num, double score) {
this.name = name;
this.age = age;
this.num = num;
this.score = score;
}
public String toString() {
return name + "\t" + age + "\t" + num + "\t" + score;
}
}
...............................................
定义一个用于将Student对象序列化的类
package com.neusoft.test1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
publicclass SerializableTest {
publicstaticvoid main(String[] args) {
Student stu_1 = new Student("wjl", 25, "47843847", 89);// 实例化两个可以被序列化的student对象
Student stu_2 = new Student("yxm", 23, "47856547", 99);
File f = new File("c:/demo/456.txt");// 保存两个对象的文件对象
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("没有被序列化时的对象如下:");
System.out.println(stu_1);
System.out.println(stu_2);
oos.writeObject(stu_1);
oos.writeObject(stu_2);
System.out.println("序列化成功!!");
oos.flush();
fos.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...............................................
定义一个用于将Student对象反序列化的类
package com.neusoft.test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
publicclass TurnSerializableTest {
publicstaticvoid main(String[] args) {
File f = new File("c:/demo/456.txt");
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Student stu_1;
stu_1 = (Student) ois.readObject();
System.out.println(stu_1);
Student stu_2 = (Student) ois.readObject();
System.out.println(stu_2);
fis.close();
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载于:https://blog.51cto.com/8174388/1325617
本文介绍了如何使用Java的Serializable接口实现对象序列化,并通过ObjectOutputStream进行序列化操作,以及如何使用ObjectInputStream进行反序列化恢复对象。具体演示了创建Student类,实例化对象并保存到文件中,然后从文件读取并打印恢复后的对象。
416

被折叠的 条评论
为什么被折叠?



