Skip to content

Saving and Restoring Data

mdsimmo edited this page Jun 30, 2018 · 1 revision

Once all objects needed to be saved are serializable (see Making Serializable Classes), the process of saving/restoring data is rather straight forwards.

Saving

// Create a top level bundle to store data in:
DataOutRoot root = new DataOutRoot();

// Write your data to `dataOut`:
root.put("level", level);
root.put("hero", hero);
//  note: there is no need to write objects that are contained by other objects

// Convert DataOut to `PData` (PrimitiveData)
PData pdata = root.toPrimitiveData();

// Create a OutputStream:
OutputStream outputsteam = new FileOutputStream(new File("save.json"));

// Write the primitive data to the output stream
new JsonLoader().write(outputsteam, pdata);

Loading

// Get an `InputStream`
InputStream inputstream = new FileInputStream(new File("save.json"));

// Read primitive data from inputstream
PData inPData = new JsonLoader().read(inputstream);

// Convert PData into DataIn
DataIn dataIn = new DataIn(inPData);

// Read out the data
hero = dataIn.read(Hero.class, "hero");
level = dataIn.read(Level.class, "level);

Clone this wiki locally