package Test2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 定义方法writeStudent(),实现对象的序列化将Student对象写到文件student.txt中
* 定义方法readStudent(),实现对象的反序列化,读取student.txt文件,获取Student对象,并调用方法study
* 在main中调用writeStudent(),readStudent()
*
* @author Administrator
*
*/
public class LiXi_Demo02 {
public static void main(String[] args) throws Exception {
Student stu[] = { new Student("张三", 14), new Student("李四", 17), new Student("王五", 12) };
writeObject(stu);
Object arr[] = readObjet();
for (int i = 0; i < arr.length; i++) {
Student s = (Student) arr[i];
System.out.println(s);
}
}
public static void writeObject(Object obj[]) throws IOException {
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(new File("student.txt")));
stream.writeObject(obj);
stream.close();
}
@SuppressWarnings("resource")
public static Object[] readObjet() throws IOException, Exception {
ObjectInputStream stream = new ObjectInputStream(new FileInputStream(new File("student.txt")));
Object object[] = (Object[]) stream.readObject();
stream.close();
return object;
}
}
|
|