老师好像没教怎么一次读取文件中的全部对象
package homework; import java.io.Serializable; public class Product implements Serializable { private String ID; private String name; private String categories; private float price; public Product(String iD, String name, String categories, float price) { super(); ID = iD; this.name = name; this.categories = categories; this.price = price; } @Override public String toString() { return "Product [ID=" + ID + ", name=" + name + ", categories=" + categories + ", price=" + price + "]"; } }
package homework;
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 Test {
public static void main(String[] args) {
Product iphone=new Product("123","iphone","telephone",4888f);
Product ipad=new Product("234","ipad","computer",5088f);
Product macbook=new Product("345","macbook","computer",10688);
Product iwatch=new Product("256","iwatch","watch",4799);
try {
FileOutputStream fos=new FileOutputStream("object.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream("object.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.flush();
Object n=null;
while((n=ois.readObject())!=null) {
Product products=(Product)ois.readObject();
System.out.println(products);
}
ois.close();
oos.close();
fos.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
自己尝试了下,发现报错
Product [ID=234, name=ipad, categories=computer, price=5088.0]
Product [ID=256, name=iwatch, categories=watch, price=4799.0]
java.io.EOFException
at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3062)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1561)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
at homework.Test.main(Test.java:28)
正在回答
同学你好,EOFException异常表示读取到文件末尾,还在继续读取就会抛出这个异常,这里同学想实现循环读取文件中的全部对象,可以参考如下代码:
这里同学需要注意,readObject返回的是序列化后的一段内容,并不是直接返回一个对象,所以这里不能使用readObject()!=null这样的方法来直接判断!
同学老师只是给出了参考代码,同学还是要根据自己的代码来自己写一遍哦!
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星