Java Tutorial/Development/Preference
Содержание
- 1 Determining If a Preference Node Contains a Specific Key
- 2 Determining If a Preference Node Contains a Specific Value
- 3 Determining If a Preference Node Exists
- 4 Determining When a Preference Node Is Added or Removed
- 5 Exporting the Preferences in a Preference Node
- 6 Exporting the Preferences in a Subtree of Preference Nodes
- 7 Export Preferences to XML file
- 8 Get childrenNames from Preferences
- 9 Get keys from Preferences
- 10 Get name and parent from Preference
- 11 Get node from Preference
- 12 Get the desired look and feel from a per-user preference
- 13 Getting and Setting Java Type Values in a Preference
- 14 Getting the Maximum Size of a Preference Key and Value
- 15 Getting the Roots of the Preference Trees
- 16 Get value from Preferences
- 17 Listening for Changes to Preference Values in a Preference Node
- 18 Preference save and load
- 19 Preferences Inspector
- 20 Put key value pair to Preference
- 21 Read / write data in Windows registry
- 22 Removing a Preference from a Preference Node
- 23 Removing a Preference Node
- 24 Retrieving the Parent and Child Nodes of a Preference Node
Determining If a Preference Node Contains a Specific Key
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
}
// Returns true if node contains the specified key; false otherwise.
public static boolean contains(Preferences node, String key) {
return node.get(key, null) != null;
}
}
Determining If a Preference Node Contains a Specific Value
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
}
public static String containsValue(Preferences node, String value) {
try {
String[] keys = node.keys();
for (int i = 0; i < keys.length; i++) {
if (value.equals(node.get(keys[i], null))) {
return keys[i];
}
}
} catch (BackingStoreException e) {
}
return null;
}
}
Determining If a Preference Node Exists
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
boolean exists = Preferences.userRoot().nodeExists("/yourValue"); // false
Preferences.userRoot().node("/yourValue");
exists = Preferences.userRoot().nodeExists("/yourValue"); // true
Preferences prefs = Preferences.userRoot().node("/yourValue");
prefs.removeNode();
// exists = prefs.nodeExists("/yourValue");
exists = prefs.nodeExists(""); // false
}
}
Determining When a Preference Node Is Added or Removed
import java.util.prefs.NodeChangeEvent;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(String.class);
prefs.addNodeChangeListener(new NodeChangeListener() {
public void childAdded(NodeChangeEvent evt) {
Preferences parent = evt.getParent();
Preferences child = evt.getChild();
}
public void childRemoved(NodeChangeEvent evt) {
Preferences parent = evt.getParent();
Preferences child = evt.getChild();
}
});
Preferences child = prefs.node("new node");
child.removeNode();
prefs.removeNode();
}
}
Exporting the Preferences in a Preference Node
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(String.class);
// Save some values
prefs.put("myString", "a string"); // String
prefs.putBoolean("myBoolean", true); // boolean
prefs.putInt("myInt", 123); // int
prefs.putLong("myLong", 123L); // long
prefs.putFloat("myFloat", 12.3F); // float
prefs.putDouble("myDouble", 12.3); // double
byte[] bytes = new byte[10];
prefs.putByteArray("myByteArray", bytes); // byte[]
// Export the node to a file
prefs.exportNode(new FileOutputStream("output.xml"));
}
}
Exporting the Preferences in a Subtree of Preference Nodes
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(String.class);
// Save some values
prefs.put("myString", "a string"); // String
prefs.putBoolean("myBoolean", true); // boolean
prefs.putInt("myInt", 123); // int
prefs.putLong("myLong", 123L); // long
// Save some values in the parent node
prefs = prefs.parent();
prefs.putFloat("myFloat", 12.3F); // float
prefs.putDouble("myDouble", 12.3); // double
byte[] bytes = new byte[10];
prefs.putByteArray("myByteArray", bytes); // byte[]
prefs.exportSubtree(new FileOutputStream("output.xml"));
}
}
Export Preferences to XML file
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
FileOutputStream fos = new FileOutputStream("prefs.xml");
myPrefs.exportSubtree(fos);
fos.close();
}
}
Get childrenNames from Preferences
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
System.out.print("Node"s children: ");
for (String s : myPrefs.childrenNames()) {
System.out.print(s + "");
}
}
}
Get keys from Preferences
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
System.out.print("Node"s keys: ");
for (String s : myPrefs.keys()) {
System.out.print(s + "");
}
}
}
Get name and parent from Preference
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
System.out.println("Node"s name: " + myPrefs.name());
System.out.println("Node"s parent: " + myPrefs.parent());
System.out.println("NODE: " + myPrefs);
}
}
Get node from Preference
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
System.out.println("userNodeForPackage: "
+ Preferences.userNodeForPackage(PreferenceExample.class));
}
}
Get the desired look and feel from a per-user preference
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.prefs.Preferences;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LookAndFeelPrefs {
public static final String PREF_NAME = "preferredLookAndFeelClassName";
/**
* Get the desired look and feel from a per-user preference. If the
* preferences doesn"t exist or is unavailable, use the default look and feel.
* The preference is shared by all classes in the same package as prefsClass.
*/
public static void setPreferredLookAndFeel(Class prefsClass) {
Preferences prefs = Preferences.userNodeForPackage(prefsClass);
String defaultLAF = UIManager.getSystemLookAndFeelClassName();
String laf = prefs.get(PREF_NAME, defaultLAF);
try {
UIManager.setLookAndFeel(laf);
} catch (Exception e) { // ClassNotFound or InstantiationException
// An exception here is probably caused by a bogus preference.
// Ignore it silently; the user will make do with the default LAF.
}
}
/**
* Create a menu of radio buttons listing the available Look and Feels. When
* the user selects one, change the component hierarchy under frame to the new
* LAF, and store the new selection as the current preference for the package
* containing class c.
*/
public static JMenu createLookAndFeelMenu(final Class prefsClass, final ActionListener listener) {
// Create the menu
final JMenu plafmenu = new JMenu("Look and Feel");
// Create an object used for radio button mutual exclusion
ButtonGroup radiogroup = new ButtonGroup();
// Look up the available look and feels
UIManager.LookAndFeelInfo[] plafs = UIManager.getInstalledLookAndFeels();
// Find out which one is currently used
String currentLAFName = UIManager.getLookAndFeel().getClass().getName();
// Loop through the plafs, and add a menu item for each one
for (int i = 0; i < plafs.length; i++) {
String plafName = plafs[i].getName();
final String plafClassName = plafs[i].getClassName();
// Create the menu item
final JMenuItem item = plafmenu.add(new JRadioButtonMenuItem(plafName));
item.setSelected(plafClassName.equals(currentLAFName));
// Tell the menu item what to do when it is selected
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// Set the new look and feel
try {
UIManager.setLookAndFeel(plafClassName);
} catch (UnsupportedLookAndFeelException e) {
// Sometimes a Look-and-Feel is installed but not
// supported, as in the Windows LaF on Linux platforms.
JOptionPane.showMessageDialog(plafmenu, "The selected Look-and-Feel is "
+ "not supported on this platform.", "Unsupported Look And Feel",
JOptionPane.ERROR_MESSAGE);
item.setEnabled(false);
} catch (Exception e) { // ClassNotFound or Instantiation
item.setEnabled(false); // shouldn"t happen
}
// Make the selection persistent by storing it in prefs.
Preferences p = Preferences.userNodeForPackage(prefsClass);
p.put(PREF_NAME, plafClassName);
// Invoke the supplied action listener so the calling
// application can update its components to the new LAF
// Reuse the event that was passed here.
listener.actionPerformed(event);
}
});
// Only allow one menu item to be selected at once
radiogroup.add(item);
}
return plafmenu;
}
}
Getting and Setting Java Type Values in a Preference
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(Main.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Save
prefs.put(PREF_NAME, "a string"); // String
prefs.putBoolean(PREF_NAME, true); // boolean
prefs.putInt(PREF_NAME, 123); // int
prefs.putLong(PREF_NAME, 123L); // long
prefs.putFloat(PREF_NAME, 12.3F); // float
prefs.putDouble(PREF_NAME, 12.3); // double
byte[] bytes = new byte[1024];
prefs.putByteArray(PREF_NAME, bytes); // byte[]
// Retrieve
String s = prefs.get(PREF_NAME, "a string"); // String
boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
int i = prefs.getInt(PREF_NAME, 123); // int
long l = prefs.getLong(PREF_NAME, 123L); // long
float f = prefs.getFloat(PREF_NAME, 12.3F); // float
double d = prefs.getDouble(PREF_NAME, 12.3); // double
bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
}
}
Getting the Maximum Size of a Preference Key and Value
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
// Get maximum key length
int keyMax = Preferences.MAX_KEY_LENGTH;
// Get maximum value length
int valueMax = Preferences.MAX_VALUE_LENGTH;
// Get maximum length of byte array values
int bytesMax = Preferences.MAX_VALUE_LENGTH * 3 / 4;
}
}
Getting the Roots of the Preference Trees
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
// Get the system root
Preferences prefs = Preferences.systemRoot();
// Get the user root
prefs = Preferences.userRoot();
// The name of a root is ""
String name = prefs.name();
// The parent of a root is null
Preferences parent = prefs.parent();
// The absolute path of a root is "/"
String path = prefs.absolutePath();
}
}
Get value from Preferences
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
for (String s : myPrefs.keys()) {
System.out.println("" + s + "= " + myPrefs.get(s, ""));
}
}
}
Listening for Changes to Preference Values in a Preference Node
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(String.class);
prefs.addPreferenceChangeListener(new PreferenceChangeListener() {
public void preferenceChange(PreferenceChangeEvent evt) {
Preferences node = evt.getNode();
String key = evt.getKey();
String newValue = evt.getNewValue();
}
});
prefs.put("key", "a string");
prefs.put("key", "a new string");
prefs.remove("key");
}
}
Preference save and load
import java.util.Arrays;
import java.util.Iterator;
import java.util.prefs.Preferences;
public class MainClass {
public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(MainClass.class);
prefs.put("key1", "value1");
prefs.put("key2", "value2");
prefs.putInt("intValue", 4);
prefs.putBoolean("booleanValue", true);
int usageCount = prefs.getInt("intValue", 0);
usageCount++;
prefs.putInt("UsageCount", usageCount);
Iterator it = Arrays.asList(prefs.keys()).iterator();
while (it.hasNext()) {
String key = it.next().toString();
System.out.println(key + ": " + prefs.get(key, null));
}
System.out.println(prefs.getInt("booleanValue", 0));
}
}
Preferences Inspector
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
public class MainClass implements PreferenceChangeListener {
private Preferences userPrefs;
public static final String NAMEPREF = "name";
public static final String EMAILPREF = "email";
public static final String AGEPREF = "age";
public static final String PHONEPREF = "phone";
public static void main(String args[]) {
new MainClass();
}
public MainClass() {
userPrefs = Preferences.userNodeForPackage(MainClass.class);
System.out.println(userPrefs.get(NAMEPREF, ""));
System.out.println(userPrefs.get(EMAILPREF, ""));
System.out.println(userPrefs.get(AGEPREF, ""));
System.out.println(userPrefs.get(PHONEPREF, ""));
userPrefs.put(NAMEPREF, "name");
userPrefs.put(AGEPREF, "Text");
userPrefs.put(EMAILPREF, "email");
userPrefs.put(PHONEPREF, "phone");
System.out.println("Preferences stored");
Preferences.userNodeForPackage(MainClass.class).addPreferenceChangeListener(this);
}
public void preferenceChange(PreferenceChangeEvent evt) {
String key = evt.getKey();
String val = evt.getNewValue();
if (key.equals(NAMEPREF)) {
System.out.println(val);
} else if (key.equals(EMAILPREF)) {
System.out.println(val);
} else if (key.equals(AGEPREF)) {
System.out.println(val);
} else if (key.equals(PHONEPREF)) {
System.out.println(val);
}
}
}
Put key value pair to Preference
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
public static void main(String args[]) throws Exception {
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node("PreferenceExample");
myPrefs.put("A", "a");
myPrefs.put("B", "b");
myPrefs.put("C", "c");
System.out.println("Node"s absolute path: " + myPrefs.absolutePath());
}
}
Read / write data in Windows registry
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] args) {
String PREF_KEY = "org.username";
// Write Preferences information to HKCU (HKEY_CURRENT_USER),HKCU\Software\JavaSoft\Prefs\
Preferences userPref = Preferences.userRoot();
userPref.put(PREF_KEY, "a");
System.out.println("Preferences = " + userPref.get(PREF_KEY, PREF_KEY + " was not found."));
// Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),HKLM\Software\JavaSoft\Prefs\
Preferences systemPref = Preferences.systemRoot();
systemPref.put(PREF_KEY, "b");
System.out.println("Preferences = " + systemPref.get(PREF_KEY, PREF_KEY + " was not found."));
}
}
Removing a Preference from a Preference Node
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
// Get the user preference node for java.lang
Preferences prefs = Preferences.userNodeForPackage(String.class);
// Remove a preference in the node
final String PREF_NAME = "name_of_preference";
prefs.remove(PREF_NAME);
// Remove all preferences in the node
prefs.clear();
}
}
Removing a Preference Node
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
boolean exists = Preferences.userRoot().nodeExists("/yourValue"); // false
if (!exists) {
Preferences prefs = Preferences.userRoot().node("/yourValue");
prefs.removeNode();
// prefs.removeNode();
}
Preferences prefs = Preferences.userRoot().node("/yourValue/child");
exists = Preferences.userRoot().nodeExists("/yourValue"); // true
exists = Preferences.userRoot().nodeExists("/yourValue/child"); // true
Preferences.userRoot().node("/yourValue").removeNode();
exists = Preferences.userRoot().nodeExists("/yourValue"); // false
exists = Preferences.userRoot().nodeExists("/yourValue/child"); // false
}
}
Retrieving the Parent and Child Nodes of a Preference Node
import java.util.prefs.Preferences;
public class Main {
public static void main(String[] argv) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(java.lang.String.class);
Preferences node = prefs.parent(); // /java
node = node.parent(); // null
String[] names = null;
names = prefs.childrenNames();
for (int i = 0; i < names.length; i++) {
node = prefs.node(names[i]);
}
}
}