我有以下代码来保存对象的ArrayList,然后再次读取它。但是它不起作用,读取显示为空。怎么解决?
一些细节:POInode实现seriazable;看起来数据被正确保存; 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)
问题是继承的变量。它不是Serializable作为类。我扩展了原始库。