我试图用Java保存/加载我的TicketSet类的实例。下面是类和类变量。 Ticket和Variable类也是Serializable。
public class TicketSet implements Serializable{
public final int setID;
public int ticketNum;
public Ticket[] tickets;
private static int xCount[];
private static int yCount[];
private static int zCount[];
private Variable x;
private Variable y;
private Variable z;
在另一个类中,我保存了TicketSet
类的实例,它似乎工作正常。在代码中,gen只是一个初始化TicketSet
的控制器类的实例。
TicketSet set;
if (f.exists()) {
FileOutputStream fileOut =new FileOutputStream(f,true);
AppendingObjectOutputStream out = new AppendingObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
} else {
FileOutputStream fileOut =new FileOutputStream(f,true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
}
要加载TicketSet的实例,我有以下代码抛出错误。
ArrayList<Integer> tickid = new ArrayList<Integer>();
tSets = new HashMap<Integer, TicketSet>();
FileInputStream fileStr = null;
ObjectInputStream reader = null;
try {
fileStr = new FileInputStream("TicketSets.ser");
reader = new ObjectInputStream(fileStr);
System.out.println(fileStr.available());
TicketSet tSet= null;
while (fileStr.available()>0) {
Object next = reader.readObject(); //ERROR HERE
if (next instanceof TicketSet) {
tSet = (TicketSet) next;
System.out.println("ID: "+tSet.setID);
tSets.put(tSet.setID, tSet);
tickid.add(tSet.setID);
} else {
System.out.println("Unexpected object type: " + next.getClass().getName());
}
}
//System.out.println("Size: "+tSets.size());
reader.close();
fileStr.close();
}
catch(IOException i) {
i.printStackTrace();
}
catch (ClassNotFoundException c) {
System.out.println("TicketSet class not found");
c.printStackTrace();
}
抛出的错误是:
ID: 7325825
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.io.ObjectStreamClass
所以我理解的是:
为什么要加载整数?有没有办法跳过除对象以外的任何东西?我应该尝试另一种方法吗?
答案 0 :(得分:0)
我在附加的ObjectOutputStream中错过了Reset()。