0
java.lang.ClassCastException: infrastructure cannot be cast to terrain 
at p2_assign_version2.main(p2_assign_version2.java:98) 

这是我试图构建文件时不断打印的错误。 由于这个错误,我无法打印我terrain.txt中的所有数据用投射错误保存文件

有没有人知道我可以如何修复错误?

和下面是导致出现错误

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(); 
     } 
    } 
+0

1)为了更快提供帮助,请发布[SSCCE](http://sscce.org/)。 2)将catch(Exception e){..']形式的代码更改为catch(Exception e){e.printStackTrace(); //非常翔实! ..' – 2013-05-11 11:19:42

+0

很明显'地形'不是从'基础设施'派生的。 – 2013-05-11 11:34:38

+0

'terrains [3] =新地形(“道路”,假); oos.writeObject(terrains [4]);'你在这里忘记了什么吗? – johnchen902 2013-05-11 11:43:21

回答

0

在ObjectInputStream中的对象是infrastructure类的一个实例,而不是terrain类的实例的集合的代码。这将工作:

(infrastructure) ois.readObject() 

这是不可能的,进一步协助您不知道更多关于它创建了terrain.txt文件的代码。要么你需要文档来准确地告诉你哪些对象被写入到该文件中,或者你需要检查写入该文件的代码,以便确切知道哪些对象被写入。

备注:Java对象没有被序列化为纯文本,因此使用.txt扩展名命名包含序列化Java对象的文件是不正确的。通常.ser扩展名用于这样的文件。