I am having problems to save an ArrayList of a object to a file and them read that. I am searching in StackOverflow and I cannot find my error...
Either I have and Classnotfound issue OR a read empty values...
Does anybody help me? Looks that writing is working well to me.
That is the code:
// calls using the CLASS
// Lets save distribution IFF asked to
if (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 (shouldLoadPoiDistribution){
Global.lastPOIloaded = 0;
GlobalWriteAndLoadPositions loader = new GlobalWriteAndLoadPositions();
Global.listOfLoadedPOIs = loader.load(Global.distributionFile);
}
///// CLASS to read and write object in file.
// The file look be correct its is created and the size varies...
// reading returns the corret size of the arraylist, but only wrong values IFF I try/catch "ois.readObject();" for ClassNotFound, otherwise, it raises an exception
package sinalgo.runtime;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import projects.nodes.nodeImplementations.POInode;
public class GlobalWriteAndLoadPositions {
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");
System.out.print("\n[Global] Trying SAVE a distribution on " + folder + nextFileItarator + ".txt" + ": ");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(POIlist);
oos.close();
fout.close();
POIlist.forEach((a)->System.out.print("POI " + a.ID + " @ (" + a.getPosition().xCoord +" , " + a.getPosition().yCoord + ") | " ));
System.out.println("\n");
}
public ArrayList<POInode> load(String file) throws IOException{
System.out.print("\n[Global] Trying LOAD a distribution: " + Global.distributionFile + " ||> ");
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, Does not find the class POInode
ois.close();
fin.close();
listOfLoadedPOIs.forEach((a)->System.out.print("POI " + a.ID + " @ (" + a.getPosition().xCoord +" , " + a.getPosition().yCoord + ") | " ));
System.out.println("\n");
return (ArrayList<POInode>) listOfLoadedPOIs;
}
}
Please, how to solve this?