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

1 回答 1

0

ObjectInputStream 中的对象是infrastructure类的实例,而不是类的实例terrain。这将起作用:

(infrastructure) ois.readObject()

如果不了解创建terrain.txt文件的代码的更多信息,就无法进一步帮助您。您需要文档来准确地告诉您哪些对象被写入该文件,或者您需要检查编写该文件的代码,以便您可以确切地知道哪些对象被写入。

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

于 2013-05-11T11:29:54.980 回答