2017-03-22 41 views
0

我有以下代碼保存對象的ArrayList,然後再次閱讀它。然而,它不起作用,讀取顯示爲空。如何解決它?從文件加載arraylist時的空對象

一些細節:POInode實現seriazable;看起來數據被正確保存;數組列表是非靜態的;

// 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和他們的一些編碼數據。這是不明確的文字數據。有一些KB ...看起來寫得很好。 – bruno

回答

0

問題是繼承的變量。它不是可串行化的類。我擴展了原始庫。