How to save a persistent variable in java even if you close the program [closed]

0

How to save the value of a variable in java so that after the program closes and reopens, the variable retains its value? Is that I have a java program that I need to execute a few functions x only once, my plan is to create a persistent boolean variable which takes true the first time the program runs. Then I just have to check its value, if it is true I do not execute the functions x and if it is false yes. I hope to explain myself well. Thanks and regards.

    
asked by Luis Ramiro 06.06.2018 в 06:52
source

1 answer

1

A very simple way to do this is using the Java preferences. This is a very simple way to store values without having to worry about creating a text file or creating a database, which in the end would end up being very laborious ways when what you want is to store a single value of Boolean type. p>

The use of the preferences is very simple, when creating the instance of this, you pass as a key the name of the package of the class where you implement it, or else, it can be the class class. This key is what you will always use to access this preference.

// Accede a las preferencias del usuario utilizando el paquete de la clase.
Preferences preferences = Preferences.userNodeForPackage(Preferencias.class);

// Almacenas las preferencias en pares clave valor.
preferences.putBoolean("verdadero", true);

// Obtienen las preferencias. En caso de que la preferencia
// no exista, retorna el valor por defecto. El valor por
// defecto de la preferencia es el que se le pasa como
// segundo parametro.
boolean verdadero = preferences.getBoolean("verdadero", false);

System.out.println(verdadero); // Imprime true
  

If you have worked with Android before, you will notice that there is a lot of similarity between these preferences and Android preferences.

I leave you the official link of the Java documentation.

link

    
answered by 06.06.2018 в 20:48