The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.prefs  [18 examples]

e409. Getting and Setting Java Type Values in a Preference

A preference node holds only string values. However, the Preferences class has convenience methods that will convert a number of basic Java types to and from strings. For example, Preferences.putByteArray() converts a byte array into a string and then saves the string value. Preferences.getByteArray() converts the string back into an array of bytes.

The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array (see e44 Serializing an Object).

See also e410 Getting the Maximum Size of a Preference Key and Value.

    // 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";
    
    // 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[]

 Related Examples
e405. Saving and Retrieving a Preference Value
e406. Determining If a Preference Node Contains a Specific Key
e407. Determining If a Preference Node Contains a Specific Value
e408. Removing a Preference from a Preference Node
e410. Getting the Maximum Size of a Preference Key and Value

See also: Events    Importing and Exporting    Nodes   


© 2002 Addison-Wesley.