I'm currently trying to save and load multiple instances of a class of type 'Player' via serialization. (This is for an assignment as an fyi).
The way the process currently works is I run the class via an ObjectOutputStream.writeObject(Player), this seems to work as I get the text file with what appears to be class data.
The problem I'm currently having is when I reverse and load the class, I'm unable to cast the object back to a player object, it is throwing an exception, however I'm not currently knowledgeable enough to figure out the exact exception.
Please find below the functions.
Save function:
public void savePlayers(ArrayList<Player> p)
{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try
{
fout = new FileOutputStream("Player.txt");
oos = new ObjectOutputStream(fout);
for(Player player: p)
{
oos.writeObject(p);
}
fout.close();
oos.close();
}
catch(Exception e)
{
System.out.println("Error is: " + e);
}
finally
{
closeStreams(fout, oos);
}
}
Load Function:
public ArrayList<Player> loadPlayers()
{
ArrayList<Player> loadedList = new ArrayList<Player>();
FileInputStream fis;
ObjectInputStream ois;
try
{
fis = new FileInputStream("Player.txt");
ois = new ObjectInputStream(fis);
while(true)
{
System.out.println("Entered loop"); //testing
Object obj = ois.readObject();
System.out.println("Read object done"); //testing
Player p = (Player)obj;
System.out.println("Casted player"); //The line here doesn't run, prints out error from exception instead and exits loop
loadedList.add(p);
System.out.println("Loop iterated");
}
}
catch(EOFException eof)
{
}
catch(Exception e)
{
System.out.println("Exception here");
}
}
Is there a better way to save the classes? Am I doing something wrong when casting?