0

I have recently started learning java and I have a basic simple game I would like to save data.

I have tiles which I use for the background. its 55x32. I only need to save the tileID. I know of some ways I could go about this by saving it all into a string possibly dividing it with a comma. Then splitting it and re-creating it back from there. But.

I have a grid which is the same thing, 15x15 but this data would require multiple things such as object ID, cost, level, energy and so forth. And they are multiple of different things. Some might have energy while others will have metal.

How could I best save this data locally?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
fireblade
  • 25
  • 1
  • 6
  • 1
    You can serialize/de-serialize a class object. You can store data in a file and read it back. And many other ways. What have you tried so far?! – Rahul Oct 23 '13 at 04:49
  • I'm still new to java, I've read this serialization everywhere but i can't understand enough of it. I have not tried anything yet because im unsure of how i would save all the data of the objects with different attributes. – fireblade Oct 23 '13 at 04:51
  • [Serialization](http://www.tutorialspoint.com/java/java_serialization.htm) is actually pretty straight forward. – ChiefTwoPencils Oct 23 '13 at 05:10
  • What about csv? It's pretty simple for understanding, http://stackoverflow.com/questions/101100/csv-api-for-java – lummycoder Oct 23 '13 at 06:57

1 Answers1

1

Serialization is the simplest option - have your objects (all of them!) implement Serializable. Then just:

File file = /* ask the user for a file name somehow - JFileChooser, whatever */
try ( ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( file ))) {
   out.writeObject ( myObject );
} catch (IOException ioe) {
    // do something if there is an error, at least this so you
    // know if something went wrong
   ioe.printStackTrace();
}

The only catch with serialization is that, if you change your classes (add methods, fields, rename things), then you won't be able to read old files in the new version of your program (there are ways to deal with that, but they are too complicated to describe here). There are various libraries that will let you serialize more flexibly, to XML or JSON. But Java serialization is a good place to start.

Tim Boudreau
  • 1,741
  • 11
  • 13