[英]Java ClassCastException while using FileInputStream
I am trying to save/load instances of my TicketSet class in Java. 我正在尝试使用Java保存/加载我的TicketSet类的实例。 Below is the class and the class variables.
下面是类和类变量。 The Ticket and Variable class are also Serializable.
Ticket和Variable类也可以序列化。
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;
In another class I save an instance of the TicketSet
class which seems to work fine. 在另一个类中,我保存了
TicketSet
类的一个实例,该实例似乎运行良好。 In the code, gen is just an instance of a controller class which initialises 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();
}
To load the instances of TicketSet, I have the following code which throws the error. 要加载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();
}
The error thrown is: 引发的错误是:
ID: 7325825
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.io.ObjectStreamClass
So what I understand is: 所以我的理解是:
Why is it trying to load an integer? 为什么要尝试加载整数? Is there a way to skip reading anything other than objects?
有没有一种方法可以跳过阅读对象以外的其他内容? Should I try an alternative approach?
我应该尝试其他方法吗?
I was missing the Reset() in my AppendingObjectOutputStream. 我在AppendingObjectOutputStream中丢失了Reset()。
ClassCastException when Appending Object OutputStream 追加对象OutputStream时发生ClassCastException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.