从二进制文件读取时ClassCastException

时间:2013-12-04 21:20:46

标签: java serialization classcastexception randomaccessfile

我在使用泛型方法读取二进制文件时得到java.lang.ClassCastException。 我试图用相同的方法读取两个不同的文件,但后来我得到了异常,我不知道为什么。

这是读取文件的通用方法中的代码: Read是类ReadBenary的方法部分。

 import java.io.ObjectInputStream;
 import java.io.FileInputStream;
 import java.io.IOException;

 public class ReadBinary{

private ObjectInputStream reader;

public boolean open(String name) {
    try {
        reader= new ObjectInputStream(new FileInputStream(name));
        return true;
    } catch (IOException exception) {
        System.err.println("Error");
        return false;
    }
}

public void close() {
    try {
        if (reader != null) {
            lector.close();
        }
    } catch (IOException exception) {
        System.err.println("Error");
    }
}

public <E> E read() {

    E object = null;
    try {
        object = (E) reader.readObject();
    } catch (ClassNotFoundException ex) {
        System.err.println("Class dont found");
        System.err.println(ex);
    } catch (IOException ex) {
        System.err.println("End of the file");
        System.err.println(ex);
    } catch (ClassCastException ex) {
        System.err.println("Class dont found");
    }
    return object;
}

这是主要代码:

 ReadBinary reader= new ReadBinary();

      if (reader.open(file3)) {
      *  Bill bill = reader.read();
        while (bill != null) {
            manejadorBill.insert(bill);
            bill = reader.read();
        }
        reader.close();
       }

    if (reader.open(file1)) {
        Customer customer= reader.read();
        while (customer != null) {
            manejadorCustomer.insert(customer);
            customer = reader.read();
        }
        reader.close();
    }

这是在文件中写入对象的方法:

public <E> void escribir(E objeto) {
    try {
        escritor.writeObject(objeto);
    } catch (IOException exception) {
        System.err.print("Error rawr");
    }
}

BillCustomer是两个独立的类。 当我尝试运行该程序时,它表示Customer无法转换为Bill

它表示错误发生在带*的行中。

2 个答案:

答案 0 :(得分:1)

您似乎Bill中没有file3个对象。 要将此更改read()检查为:

public <E> E read() {
    Objject obj;
    E object = null;
    try {
          obj = reader.readObject();
          System.out.println(obj.getClass().getName())       
          object = (E) obj;
    } catch (ClassNotFoundException ex) {
        System.err.println("Class dont found");
        System.err.println(ex);
    } catch (IOException ex) {
        System.err.println("End of the file");
        System.err.println(ex);
    } catch (ClassCastException ex) {
        System.err.println("Class dont found");
    }
    return object;
}

查看实际类型。

答案 1 :(得分:0)

ClassCastException表示写入流的下一个对象实际上不是Bill。检查写入对象的代码,以查看它实际编写的对象类型。一些System.out.printlns可能有助于准确查看正在编写的内容。

相关问题