【问题标题】:Java ClassCastException while using FileInputStream使用 FileInputStream 时出现 Java ClassCastException
【发布时间】:2014-02-12 00:24:55
【问题描述】:

我正在尝试在 Java 中保存/加载 TicketSet 类的实例。下面是类和类变量。 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;

在另一个类中,我保存了一个 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

所以我的理解是:

  • 第一个 TicketSet 加载良好... ID=73225825
  • 然后它尝试从文件中加载一个整数,而不是 TicketSet 对象。

为什么要加载整数?有没有办法跳过阅读对象以外的任何内容?我应该尝试其他方法吗?

【问题讨论】:

标签: java classcastexception fileinputstream fileoutputstream


【解决方案1】:

我的 AppendingObjectOutputStream 中缺少 Reset()。

ClassCastException when Appending Object OutputStream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    相关资源
    最近更新 更多