lundi 23 février 2015

Serializing objects referenced in my arraylist into one file, and then loading them back into that arraylist



I know similar questions have been asked many times, but I didn't find a question that was actually the same - apologies if I missed one.


I am trying to make a little game. The game stores my characters (spirits) into an arraylist. The spirits are created with different characteristics by creating different instances of my Spirit class. Then I store that instance into my arraylist that holds my party. The arraylist holds 3 elements.


I want to serialize all of the fields of these instances, save them to a file, and then load them again and store them back in their proper positions in the arraylist (essentially save/load in my game).


I have been advised to use kyro for serialization so I am using that. I am pretty sure the code is very similar though, and I have to imagine the way this problem is solved is basically the same.


This is my code right now



public void usekryo(){

Kryo kryo = new Kryo();
kryo.register(Spirits.class);
Spirits writespirit;
Spirits readspirit;

for(int i=0;i<3;i++) { try (Output output = new Output(new FileOutputStream("spirits.ser"))) {
System.out.println("loop is going");
writespirit = OwnedSpirits.myspirits.get(i);
kryo.writeClassAndObject(output, writespirit);
} catch (FileNotFoundException ex) { System.out.println("fail"); } }

Spirits blankarray = new Spirits();
OwnedSpirits.myspirits.set(0, blankarray);
OwnedSpirits.myspirits.set(1, blankarray);
OwnedSpirits.myspirits.set(2, blankarray);

System.out.println(OwnedSpirits.myspirits.get(2).species);

for(int i=0;i<3;i++) { try (Input input = new Input(new FileInputStream("spirits.ser"))) {
System.out.println("now it's loading");
readspirit = (Spirits) kryo.readClassAndObject(input);
OwnedSpirits.myspirits.set(i, readspirit);

} catch (FileNotFoundException ex) { System.out.println("fail"); } }

System.out.println(OwnedSpirits.myspirits.get(0).species);
System.out.println(OwnedSpirits.myspirits.get(2).species);





}


This ends up doing exactly what I thought it would do. I mean I knew this wouldn't solve my problem but I was just making sure I was using kyro correctly.


Anyways, it makes an instance of my spirit class, loads the value in the first index of my arraylist, then serializes this new instance. So far so good.


But then it does it again, and overwrites what I wrote the first time. Then does it a 3rd time. So the only values that actually get saved are what is in index [2] of my arraylist.


Then, when I read that file back and write it again, all 3 indexes of my arraylist are filled with what was initially just index [2] of my arraylist.


So how in the world would I write this so that all 3 indexes are output to one file, and then input back into their proper indexes?


I am hoping this isn't super complicated, but I am definitely worried that it is.




Aucun commentaire:

Enregistrer un commentaire