【发布时间】:2017-08-13 21:59:30
【问题描述】:
我有以下代码来保存一个对象的 ArrayList,然后再次读取它。但是它不起作用,读取显示为空。如何解决?
一些细节:POInode 实现了可串行化;看起来数据已正确保存;数组列表是非静态的;
// 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();
}
}
【问题讨论】:
-
文件是空的吗?有什么异常被抛出?
-
你需要学习使用调试器。这将为您节省数小时和数小时。检查列表包含的内容在写入之前。写入时检查文件是什么。读取时检查文件是什么。阅读后检查列表包含的内容。仅当您对所有这些问题都有明确的答案时才提出问题。 “读取显示为空”太模糊了,您发布的代码无法重现问题。
-
无异常,运行良好。开头看起来像 POInode 描述,它们是一些编码数据。它不是明文数据。有一些知识库...看起来写得很好。
-
我建议您可能正在阅读错误的文件或类似的错误
标签: java file serialization arraylist deserialization