-3

So I'm in the process of developing a Java IRC bot as a bit of a side project for a friend of mine, and while development is going well, I'm a little unsure as how to save the current state of certain variables in between sessions. It doesn't have a GUI, so I didn't think that it would be too complex, but my searching efforts have been futile thus far.

Thanks.

  • 2
    Please narrow this question down, unless the answer you want is something like this: "Write the values to a file in the file-system. On start-up check if the well known file (in the previous sentence) exists, if it does; then load the values from that file. Otherwise, set the values to defaults." – Elliott Frisch May 12 '14 at 20:18
  • As asked, the answer is in the question: Q. How to save the state between sessions? A. Save the state between sessions. – David Conrad May 12 '14 at 20:35
  • https://stackoverflow.com/questions/3784657/what-is-the-best-way-to-save-user-settings-in-java-application – Troyseph Nov 13 '17 at 20:44

1 Answers1

0

It will depend on the sort of variables you want to keep, but all methods will require you to write some sort data to a file.

If you only need to keep a handful of variables, you could consider implementing a .config file that could be a simple delimited text file.

If it's an entire object that you want to keep track of, say, a player in an irc game, one option you have is to parse the object into JSON, and save it to a textfile, for reading later. You can use Gson for this

example for a 'player' object:

public String savePlayer(String playerName){
    Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
    String playerFile = System.getProperty("user.dir")+"\\players\\"+playerName;
    String jsonplayers = gsonPretty.toJson(players.get(playerName));
    try{
        FileWriter writer = new FileWriter(playerFile+".json");
        writer.write(jsonplayers);
        writer.close();
        return "Player file saved successfully!";

    }catch(Exception e){
        e.printStackTrace();
    }
    return "Something went wrong";
}

you can then create a load method that either has the file name hard coded, or a string input to determine which file to load, and use something like:

playerFromJson = gson.fromJson(jsonString, Player.class);

to use that object in the code

C_Sto
  • 218
  • 1
  • 7