程序报了一个错误: Exception in thread "main" 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 ObjectStreamTest.read(ObjectStreamTest.java:27) at ObjectStreamTest.main(ObjectStreamTest.java:14)
请问怎么解决? 数据可以正常输出。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* 需求:通过序列化流把三个对象写入文本文件,并遍历。
*/
public class ObjectStreamTest {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
read();
}
// 读取多个对象
private static void read() throws IOException, ClassNotFoundException {
// 创建反序列化流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"2.txt"));
// // 读取数据
// 读取
try {
Object obj = null;
while ((obj = ois.readObject()) != null)
{
System.out.println(obj);
}
}
catch (Exception e)
{
//e.printStackTrace();
}
//释放资源
ois.close();
}
// 写多个对象
private static void write() throws IOException {
// 创建序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"2.txt"));
// 创建对象
Person p1 = new Person();
p1.setName("李四");
p1.setAge(20);
Person p2 = new Person();
p2.setName("张三");
p2.setAge(38);
Person p3 = new Person();
p3.setName("王五");
p3.setAge(30);
// 写入数据
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);
oos.close();
}
}
import java.io.Serializable;
public class Person implements Serializable {
// 产生一个固定的序列号id值
// private static final long serialVersionUID = -6838499878718774345L;
private String name;
private int age;
// public int age;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "name:" + name + ",age:" + age;
}
}
|