java.lang.ClassCastException: infrastructure cannot be cast to terrain
at p2_assign_version2.main(p2_assign_version2.java:98)
This is the error that is constantly being printed when I try to build my file. Due to this error i m not able to print all my datas in my terrain.txt
Does anyone here know how I can fix the error?
and below is the set of code that is causing the error to appear
File terrain=new File("terrain.txt"); //To create file
boolean tExist=terrain.exists();
terrain[]terrains = new terrain[100];
if(!tExist)
{
try
{
FileOutputStream fos = new FileOutputStream("terrain.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
terrains[0] = new terrain("Grass", true);
oos.writeObject(terrains[0]);
terrains[1] = new terrain("Water", false);
oos.writeObject(terrains[1]);
terrains[2] = new terrain("Pavement", false);
oos.writeObject(terrains[2]);
terrains[3] = new terrain("Road", false);
oos.writeObject(terrains[4]);
terrains[5] = new terrain("Drainage", false);
oos.writeObject(terrains[5]);
terrains[6] = new terrain("Hill", false);
oos.writeObject(terrains[6]);
terrains[7] = new terrain("Bushes", false);
oos.writeObject(terrains[7]);
terrains[8] = new terrain("Tree", false);
oos.writeObject(terrains[8]);
oos.flush();
oos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
FileInputStream fis=new FileInputStream("terrain.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
for (p=0; p<terrains.length; p++)
{
if(terrains[p] == null)
{
//this is the line that causes error to be printed//
terrains[p] = (terrain) ois.readObject();
}
}
ois.close();
}
catch(EOFException eof)
{
}
catch(FileNotFoundException fnfe)
{
System.out.println("There seems to be a problem reading from the file");
}
catch(Exception e)
{
e.printStackTrace();
}
}
The object in the ObjectInputStream is an instance of the infrastructure
class, not an instance of the terrain
class. This will work:
(infrastructure) ois.readObject()
It is not possible to help you further without knowing more about the code which created your terrain.txt
file. Either you need documentation which tells you exactly which objects were written to that file, or you need to examine the code which wrote the file so you can know exactly which objects were written.
Side note: Java objects are not serialized as plain-text, so it is not correct to name a file containing serialized Java objects with a .txt
extension. Usually the .ser
extension is used for such files.