package com.java.oop.gui;
import java.io.Serializable;
//Serializable标记接口,不用现实任何方法
public class Student implements Serializable {
// 构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
// 一个ID标识
static final long serialVersionUID = 42L;
// 属性
private String name;
private int age;
// 覆盖Object方法,实现自己想打印数据
public String toString() {
return "姓名:" + name + "\t年龄:" + age;
}
}
package com.java.oop.gui;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//实现对象的序列化,和反序列化
public class ObjectDemo {
// 实现对象序列化方法
public static void save() {
// 对象序列化
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream("Student.txt"));
os.writeObject(new Student("张三", 20));
os.writeObject(new Student("李四", 25));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (os != null)
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 对象反序列化方法
public static void load() {
// 对象反序列化
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("Student.txt"));
// 定义一个变量接收返回的对象
Object obj = null;
while((obj=ois.readObject())!=null){ //我想循环读取文件中的对象,但是读完文件里面的对象 就会出现异常. 现在文件中有两个对象,但是读第三次就会出现异常。
Student stu=(Student)obj;
System.out.println(stu); }
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EOFException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 实现序列化存储数据
save();
// 实现反序列化读取数据
load();
}
}
--------------------------------------------------------
异常
姓名:张三 年龄:20
姓名:李四 年龄:25
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2596)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at com.java.oop.gui.ObjectDemo.load(ObjectDemo.java:52)
at com.java.oop.gui.ObjectDemo.main(ObjectDemo.java:85)
|