【发布时间】:2016-04-04 21:23:45
【问题描述】:
我在从文本文件中读取对象时遇到了一点问题,因为它会引发以下错误;
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to stock.control.system.StockItem
这是哪一行;
StockItem result = (StockItem) ois.readObject();
以下是我保存文件的方法;
try { FileOutputStream fout = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(StockItems); }
catch (java.io.FileNotFoundException error) {
System.out.println("FILE NOT FOUND!");
}
这是我为将文件加载回对象 ArrayList 所做的工作;
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("LOADING DATA ...");
StockItem result = (StockItem) ois.readObject();
ois.close();
System.out.println(result.getItemID() + ", " + result.getItemDesc()
+ ", " + result.getPrice() + ", " + result.getQuantity() + ", "
+ result.getReOrderLevel()); // used for testing
} catch (java.io.FileNotFoundException error) {
System.out.println("FILE NOT FOUND!");
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(StockArrayList.class.getName()).log(Level.SEVERE, null, ex);
}
如果有任何地方可以教育我,使其能够正确完成,将不胜感激。
【问题讨论】:
-
什么是
StockItems?这是StockItem实例吗? -
您序列化了一个
StockItem[]类型的对象,并希望将未序列化的对象转换为StockItem类型?这必须失败。再次将其反序列化为数组。 -
看起来您正在编写一个数组列表“StockItems”,但试图读取一个“StockItem”。
标签: java file object save load