Search code examples
javajarstore

How To Store Values Within JAR \ Java Project


I've looked around for this for a while now and haven't really found anything conclusive.

I have a java project that I want to run (Desktop Application) and I wish, upon the first startup, for the user to enter a few values which will remain the values of the respective variables forever, i.e. when I re-run the jar file, the changed values will show instead of the initial packaged values.

I tried using xml to store the file within the jar and read and write to it, no success. So now I've opt to do this.

However if there's a simpler way, please enlighten me, this is one of the initial steps of a bigger project for me and I refuse to go on till I solve this.


Solution

  • If you have only a few values to store, not a large file, then Preferences is the solution designed for this.

    Preferences prefs = Preferences.userRoot().node("/com/yourcompany/yourprogram");
    
    int value = prefs.getInt("key", -1);
    if(value == -1) {
       prefs.put("value", Integer.parseInt(
                 JOptionPane.showInputDialog("Enter value:"));
       prefs.flush();
    }