本帖最后由 戴振良 于 2012-4-5 12:03 编辑
实例功能:通过ObjectOutputStream类保存一个学生对象的信息,再通过ObjectInputStream类把学生信息读取出来
文件一:- import java.io.*; -----------------------------------------》代码1
- //import java.io.Serializable;-----------------------------------------》代码2
- public class SerializableTest implements Serializable {
- int ID; String name; int age; String department;
- public SerializableTest(int ID,String name,int age,String department) {
- this.ID = ID; this.name = name; this.age = age; this.department = department;
- }
- public String toString() {
- return "ID:" + ID + ",姓名: " + name + ",年龄: " + age + "," + department + "系";
- }
- }
复制代码 文件二:- import java.io.*;
- public class Serializable {
- public static void main(String args[]) throws Exception {
-
- SerializableTest stu1 = new SerializableTest(1,"戴振良",25,"Java软件开发");
- SerializableTest stu2 = new SerializableTest(2,"戴竹飞",21,".NET软件开发");
-
- FileOutputStream fos = new FileOutputStream("student.txt");
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(stu1);
- oos.writeObject(stu2);
- oos.close();
-
- FileInputStream fis = new FileInputStream("student.txt");
- ObjectInputStream ois = new ObjectInputStream(fis);
- SerializableTest stu3 = (SerializableTest)ois.readObject();
- SerializableTest stu4 = (SerializableTest)ois.readObject();
- ois.close();
-
- System.out.println(stu3);
- System.out.println(stu4);
-
- }
- }
复制代码 第一次我在文件一用的是“代码1“,运行通过了,然后我修改了一下toString方法,结果运行就不通过了,显示的异常信息为:
然后就是我怎么改回去之前的代码都通不过了,千找万找找不到原因{:soso_e111:} ,最后我把导入的语句改用“代码2”,嘿,通过了,实在是想不明白是为什么?我看的是张孝详老师的视频,他的就是用“代码1”的,而且运行正常,为什么我的不行?哪位高人指点指点啊!不信可以复制代码试一下 |