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