项目场景:
利用对象流循环输入同一种数据类型的数据
问题描述
ObjectInputStream中的readObject():
没有读到文件末尾的返回值,导致抛出EOFException异常:
Exception in thread "main" java.io.EOFException
解决方案:
第一种方法:利用try-catch加以判断:
while(true){
try {
Dog dog = (Dog)ois.readObject();
System.out.println(dog.age);
}catch (EOFException e){
break;
}
}
第二种方法:利用文件输入流加以判断:(这种方法我不知道是如何实现的,在老师的源码里搬来的)
while (fileInputStream.read() != -1) {
fileInputStream.skip(-1L);
Dog dog = (Dog)ois.readObject();
System.out.println(dog.age);
}
第三种方法:在输出文件时最后输出一个null,利用null加以判断(这种方法不好,仅限于要添加的元素没有null时):
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mmm.mmm"));
oos.writeObject(new Dog(1));
oos.writeObject(new Dog(2));
oos.writeObject(new Dog(3));
oos.writeObject(null);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mmm.mmm"));
Object obj ;
while((obj= ois.readObject())!=null){
Dog dog = (Dog)obj;
System.out.println(dog.age);
}
ois.close();
第四种方法:在输出文件时记录写入的个数,利用个数加以判断:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mmm.mmm"));
oos.writeObject(new Dog(1));
oos.writeObject(new Dog(2));
oos.writeObject(new Dog(3));
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mmm.mmm"));
int i = 3;
while(i--!=0){
Dog dog = (Dog)ois.readObject();
System.out.println(dog.age);
}
ois.close();