Java对象的持久化主要使用
ObjectInputStream与ObjectOutputStream类 来实现!
public class Student implements Serializable {
String name;
int id ;
int age;
String department;
public Student(String name, int id, int age, String department) {
this.age = age;
this.department = department;
this.id = id;
this.name = name;
}
public static void saveObjects(Student student, String fileName) {
FileOutputStream os = new FileOutputStream("fileName.dat");
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(student);
}
public static Student readObjects(String fileName) {
Student student;
Object obj;
try{
FileInputStream is = new FileInputStream("fileName.dat");
ObjectInputStream ois = new ObjectInputStream(is);
obj = ois.readObject();
}catch (Exception e) {
e.printStackTrace();
}
if(obj instanceof Student){
Student stu= (Student)obj;
return stu;
}
return null;
}