Saving user changed variables

Alright i think im sounding really stupid about this but i have recently made a text based rpg and the entire game is based on variables so i was wondering how i could make a save game button or something that saves all the variables as they are and a load button… so pretty much you would name your save file or somethin and you could then load it…

i have never done this before and i have been searching google for about 2 hours now and i come up with nothing.

anyways if anyone has any helpful code or tutorial links they would be greatly apreciated, and if you would need my game to look at it to be able to help me im on msn and would gladly give you the executable Jar file for it.

Im currently on messenger Sluigi_91@hotmail.com

Thanks for any help!!

One of the easier ways would be to use Properties. With this class, you can set variables using setProperty, retrieve them with getProperty, save them to a file with the ‘store’ method, and load them from a file with the ‘load’ method.

The advantage to this is that it is extremely easy to load/save variables, but the catch is, the file is very readable and thus extremely easy for the end-user to edit (if that is something you’re concerned about)

So let’s say you have a text file, variables.txt:

And you have this code…


import java.io.*;
import java.util.*;
public class Test {
	public static void main(String args[]) {
		Properties vars = loadVars();
		System.out.println(vars.getProperty("player.name")); // John Smith
		System.out.println(vars.getProperty("player.age")); // 22

		vars.setProperty("player.age","23"); // changes age to 23
		saveVars(vars); // saves changes to file
	}
	public static Properties loadVars() {
		Properties p = new Properties();
		try {
			InputStream in = new FileInputStream("variables.txt");
			p.load(in);
			in.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return p;
	}
	public static void saveVars(Properties vars) {
		try {
			OutputStream out = new FileOutputStream("variables.txt");
			vars.store(out,null);
			out.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The first time you run that… it will print “John Smith” with age 22. The second time you run it, it will display 23.

Other options would be to create your own file format, maybe a binary format, an INI file, or an XML file.

Another option is creating a Serializable ‘Variables’ class whose only purpose is to track variables and be able to be serialized to a file. This option is not much more advanced than using Properties, so it may be worth looking into.

Good luck

Using Serializable would also allow you to store your variables in a typed manner, so you don’t have to convert from/to strings like with the Properties approach. Google for java serialization tutorial to get more info.

thank you for the help!