public class Test{ public static void main(String args[]){ Store store = new Store(); FileOutputStream fos; ObjectOutputStream oos = null; try{ fos = new FileOutputStream(new File("table.obj")); oos = new ObjectOutputStream(fos); }catch(IOException e1){ e1.printStackTrace(); }
这继续包含一堆更多的代码,但我认为真正重要的是我的“Q”案例……
case "Q": System.out.println("Good-Bye!"); try{ oos.writeObject(store); oos.flush(); oos.close(); }catch(IOException e){ e.printStackTrace(); } System.exit(0); break;
当我尝试将所有数据保存到我的.obj文件并关闭流并退出我的程序时,我得到所有这些错误……
java.io.NotSerializableException:Item
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.Hashtable.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
在Test.main(Test.java:143)
我不确定这些错误大多数意味着什么,或者为什么我会得到它们,甚至不知道如何修复它们.谁能帮我?
编辑:商店类
import java.io.Serializable; import java.util.Hashtable; public class Store implements Serializable{ Hashtable<String,Item> stockedItems = new Hashtable<String,Item>(); public boolean addItem(String code){ if(stockedItems.containsKey(code)){ stockedItems.get(code).incrementQuantity(); return true; } return false; } public boolean removeItem(String code){ if(stockedItems.containsKey(code)){ stockedItems.get(code).decrementQuantity(); return true; } return false; } public boolean findItem(String code){ if(stockedItems.containsKey(code)){ return true; } return false; } }
**我的HashTable包含不实现Serializable的Item对象.我现在修复了哪个.程序运行和Q案例工作正常!现在是我的U案不起作用,这里是……
case "U": try{ FileInputStream fis = new FileInputStream("table.obj"); ObjectInputStream ois = new ObjectInputStream(fis); store = (Store)ois.readObject(); ois.close(); }catch(IOException | ClassNotFoundException e){ e.printStackTrace(); } break;
这种情况的目的是允许用户选择是否要使用存储在我的.obj文件中的数据.我试图使用这种情况时得到这些错误
at java.io.ObjectInputStream $BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
在Test.main(Test.java:142)
解决方法
UPDATE
根据您更新的问题,看起来Item类也需要实现Serializable.实际上,这正是异常的第一行所说的:
java.io.NotSerializableException: Item