Java Preference Get getStringArray(final String key, final String[] defaultValue)

Here you can find the source of getStringArray(final String key, final String[] defaultValue)

Description

Gets an array of string values from the preferences object

License

Open Source License

Parameter

Parameter Description
key the string used to save the string to be retrieved
defaultValue the value to be returned in case an error is encountered

Return

the stored value if possible, defaultValue otherwise

Declaration

public static String[] getStringArray(final String key, final String[] defaultValue) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.prefs.Preferences;

public class Main {
    /**/*from w  w  w. ja v a  2s .c om*/
     * The preferences node to load/save from/to
     */
    private static final Preferences prefs = Preferences.userRoot().node("/edu/colostate/vchill");

    /**
     * Gets an array of string values from the preferences object
     *
     * @param key          the string used to save the string to be retrieved
     * @param defaultValue the value to be returned in case an error is encountered
     * @return the stored value if possible, <code>defaultValue</code> otherwise
     */
    public static String[] getStringArray(final String key, final String[] defaultValue) {
        try {
            String val = prefs.get(key, arrayToString(defaultValue));
            if (val.equals(""))
                return new String[0];
            return val.split("\\*");
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * Converts a String[] to a single String
     *
     * @param value the String[] to convert
     * @return the contents of <code>value</code> concatenated, with "<code>*</code>" as separator
     */
    private static String arrayToString(final String[] value) {
        if (value == null || value.length == 0)
            return "";
        StringBuilder buff = new StringBuilder(value[0]);
        for (int i = 1; i < value.length; ++i)
            buff.append("*").append(value[i]);
        return buff.toString();
    }
}

Related

  1. getPreference(String key, Boolean defaultValue)
  2. getPreferences()
  3. getPreferences(final Class preferencesClass)
  4. getPrefs(Class cls)
  5. getPrefsStrings(Preferences prefs, String key)
  6. getUserPreferences()
  7. getUserPreferences()
  8. getUserPreferences(final String preferenceGroup)
  9. getUserPrefsNode(Object mainClassInstance)