2017-03-22 5 views
0

다음 코드를 사용하여 객체의 ArrayList를 저장 한 다음 다시 읽습니다. 그러나 작동하지 않으면 읽기가 비어있는 것으로 나타납니다. 그것을 해결하는 방법?파일에서 arraylist를로드 할 때 빈 객체

일부 세부 정보 : POINode는 seraserable을 구현합니다. 데이터가 정확하게 저장된 것처럼 보입니다. arraylist는 정적이 아닙니다.

// READ & Write Class: 

public GlobalWriteAndLoadPositions(){ 
} 
public void write(String folder, List<POInode> POIlist) throws IOException { 

    int nextFileItarator = (int) Files.list(Paths.get(folder)).count(); 
    nextFileItarator++; 
    FileOutputStream fout= new FileOutputStream(folder + nextFileItarator + ".txt"); 

    ObjectOutputStream oos = new ObjectOutputStream(fout);  
    oos.writeObject(POIlist); 
    oos.close(); 

    // the next line shows the arraylist full of objects and the File looks fine. (non-clear text file, but full of data) 
    POIlist.forEach((a)->System.out.print("POI " + a.ID + " @ (" + a.getPosition().xCoord +" , " + a.getPosition().yCoord + ") | ")); 
    System.out.println("\n"); 
} 


@SuppressWarnings("unchecked") 
public ArrayList<POInode> load(String file) throws IOException, ClassNotFoundException{ 

    FileInputStream fin = new FileInputStream(file); 
    ObjectInputStream ois = new ObjectInputStream(fin); 
    List<POInode> listOfLoadedPOIs = new ArrayList<POInode>(); 

    listOfLoadedPOIs = (ArrayList<POInode>) ois.readObject(); // THIS LOOK WRONG, I MEAN,it is my guess 

    ois.close();  

    // the following command shows the correct size list, but empty values! 
    listOfLoadedPOIs.forEach((a)->System.out.print("POI " + a.ID + " @ (" + a.getPosition().xCoord +" , " + a.getPosition().yCoord + ") | ")); 
    System.out.println("\n"); 

    return (ArrayList<POInode>) listOfLoadedPOIs; 
} 

//Class usage: 

if (Global.shouldSavePoiDistribution){ 

     List<POInode> listOfPOIs = new ArrayList<POInode>(); 
     for(Node n : Runtime.nodes) { 
      if (n instanceof POInode){ 
       listOfPOIs.add((POInode) n);      
      } 
     } 

     GlobalWriteAndLoadPositions saver = new GlobalWriteAndLoadPositions(); 
     saver.write(Global.distributionFolder,listOfPOIs); 
    } 

// lets load a distribution IFF asked to 
if (Global.shouldLoadPoiDistribution){ 

    GlobalWriteAndLoadPositions loader = new GlobalWriteAndLoadPositions(); 
    try { 
     Global.listOfLoadedPOIs = loader.load(Global.distributionFile); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 
+0

파일이 비어 있습니까? 모든 예외가 발생 했습니까? –

+0

디버거를 사용하여 학습해야합니다. 시간과 시간을 절약 할 수 있습니다. 쓰여지기 전에 목록에 * 들어 있는지 확인하십시오. 작성시 파일이 무엇인지 확인하십시오. 읽을 때 파일이 무엇인지 확인하십시오. 읽은 후 목록에 무엇이 들어 있는지 확인하십시오. 이 모든 질문에 대한 명확한 답이있을 때만 질문하십시오. "읽기가 비어있는 것처럼 보임"은 너무 애매합니다. 게시 한 코드가 문제를 재현 할 수있는 방법이 없습니다. –

+0

예외는 없습니다. 정상적으로 실행됩니다. 시작은 POINode descrition과 일부 인코딩 된 데이터처럼 보입니다. 일반 텍스트 데이터가 아닙니다. 몇 킬로바이트가 있습니다 ... 그 글씨는 괜찮습니다. – bruno

답변

0

문제는 상속 된 변수입니다. 그것은 클래스로 Serializable되지 않았습니다. 원본 라이브러리를 확장했습니다.