I get a java.lang.ClassCastException
while reading a binary file with a generic method.
I was trying to read two diferent files with the same method but then I get the exception and I dont know why.
This is the code in the method generic for read the file:
Read
is a method part of the Class 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;
}
This is the code in the main:
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();
}
This is the method that write the objects in the file:
public <E> void escribir(E objeto) {
try {
escritor.writeObject(objeto);
} catch (IOException exception) {
System.err.print("Error rawr");
}
}
Bill
and Customer
are two independent class.
When i try to run the program it says that Customer
cant be cast as Bill
.
It says that the error occurs in the line with *.
It seems that you don't have
Bill
objects infile3
. To check this changeread()
to:to see what are actual types.