How can i save the value of a variable in my program and then reuse it at the next program run ? I don't want to do it with file write/read.
3 Answers
Use the Java Preferences API.
import java.util.prefs.*;
public class Example {
// Preference key
private static final String FRUIT = "fruit";
public void savePreference(String favoriteFruit) {
Preferences prefs = Preferences.userNodeForPackage(Example.class);
prefs.put(FRUIT, favoriteFruit);
}
public String readPreference() {
Preferences prefs = Preferences.userNodeForPackage(Example.class);
return prefs.get(FRUIT, "default");
}
}
The data is stored based on the fully-qualified name of your class, so your package name and class name are relevant. From the documentation for the Preferences class:
This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.
Comments
One can store settings using java.util.prefs.Preferences. For two target groups: normally user settings, and less often application/system settings. They can use the platform settings, like under Windows.
There exists however also the possibility to store the settings as XML, which is a cleaner way, as it does not touch the Windows registry, which might be protected. Then a customary location would be inside a directory like ".myapp" under the directory System.getProperty("user.home").
Comments
You can use an in-memory key-value store like Redis, or an in-memory database like H2. But this may be overkill depending on your needs.
don't want to do it with file write/readuse database? But why do you want to do this?