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

파일을 만들 때 계속 인쇄되는 오류입니다. 이 오류로 인해 내 terrain.txt의 모든 데이터를 인쇄 할 수 없습니다.캐스팅 오류가있는 파일 저장

여기 오류를 해결하는 방법을 알고있는 사람이 있습니까? 아래

오류가 ObjectInputStream에있는 물체가 infrastructure 클래스의 인스턴스가 아닌 terrain 클래스의 인스턴스

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(); // 매우 유익한! ..' –

+0

잘 '지형'은 '기반 시설'에서 파생되지 않습니다. –

+0

'지형 [3] = 새로운 지형 ("도로", 거짓); oos.writeObject (terrains [4]); '여기에 아무것도 잊었 니? – johnchen902

답변

0

나타나는 원인 코드의 세트이다. 이것은 작동합니다 : 당신의 terrain.txt 파일을 생성 한 코드에 대한 자세한 내용을 모르고 더 당신을 도울 수 없습니다

(infrastructure) ois.readObject() 

. 어느 개체가 해당 파일에 쓰여졌는지 정확하게 알려주는 문서가 필요하거나 파일을 작성한 코드를 검사하여 작성된 개체를 정확히 알 수 있어야합니다.

사이드 노트 : Java 객체는 일반 텍스트로 직렬화되지 않으므로 .txt 확장자를 가진 직렬화 된 Java 객체를 포함하는 파일의 이름을 지정하는 것은 올바르지 않습니다. 일반적으로 .ser 확장이 이러한 파일에 사용됩니다.