Java, How to save values in a permanent file and load from that
I want to be able to pull values from a file that is saved, and that I can edit, and add to from in the program or just ou开发者_JAVA技巧tside of it.
Just a basic list of values.
this = that
this2 = that2
this3 = that3
And then query this, and get that out of it.
What is the best way to do this?
You can use either Properties, if you use your own files; or Preferences if you want the location to be default.
A comparison between the two APIs is found here.
As to the kind of values, theoretically anything could be stored (by serializing to String), but the APIs are best suited to fundamental types like String, Integer and the like.
In your case I'd recommend Properties as these use a text file (the name provided by you), which you can edit with any tool you want. Preferences might be stored in the Windows registry (as far as I know) which may not be suitable for you.
If you want to use Preferences, here is some exampe code:
In your class MyClass, declare..
private Preferences preferences = Preferences.userNodeForPackage(MyClass.class);
private final String item1 = "item1"; // These are the keys (names) to identify your
private final String item2 = "item2"; // items in storage.
This code will retrieve a value..
preferences.getInt(item1, 0); // the 0 is a default that will be returned
// if a stored value can't be retrieved.
This code will store a value..
preferences.putInt(item1, 4); // store an int in item1
As mentioned by @extraneon, on Windows, these will be stored in the registry. Other systems may use a file stored in the user's home directory. I only show storing and retrieving int
s but you can store many other basic types too.
You should take a look at the documentation for Preferences.userNodeForPackage()
to fully understand what it does. This will associate the stored items with your application/class.
精彩评论