问题
I have created a Swing Application- GUI containing fields like TextFields, Labels, CheckBoxes and ComboBoxes. When the user enters some information, I want the details of the textfields, comboboxes and checkboxes to be saved into a file, and the next time when a user opens this Window, I want the details that have been saved in the file, i.e. those that have been entered by the user the previous time to be loaded into the GUI. Can anyone please help me in doing this? I hope you understand the question, if not I will explain in a more detailed manner.
Thank you so much in advance.
回答1:
Here is a simple example using the java.util.prefs package:
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
The way preferences are saved is OS-dependent. On Windows, it will use the registry.
Examples of use: http://www.exampledepot.com/egs/java.util.prefs/pkg.html
回答2:
The simplest way is to use java.util.Properties
that is able to store its content in file (properties or xml format).
If you want more you can use XML. You can either generate and parse it yourself (using DOM or SAX) or, better use higher level API (e.g. JaxB).
You can also use configuration package The list can be continued...
回答3:
If the config files don't have to be editable using a text editor just serialize your config to a file and deserialize it when you need to read it.
Otherwise have a look a the Properties
class that allows you to write key-value pairs as either properties files or XML. You might have to do some conversion from string to the value you need though, i.e. myproperty=true
would return the string "true"
for key myproperty
and you'd need to parse it into a boolean.
回答4:
If you want some structure to your configuration files and dont like the flat java properties format or messy XML tagging then consider using JSON which is a very nice and clean format for storing any kind of data structure.
http://json.org/java/
It also supports XML formats so its easy to switch between these if you need it in XML format for some reason. JSON is also used as a simple data protocol for web based apps if you get into that at some stage.
来源:https://stackoverflow.com/questions/8037339/configuration-files-in-java