Search code examples
javaexceptionjarpreferences

Preferences in Java


I would store my object inside the .jar using java preferences.

I convert my object into a String and i store it.

I use this code to save it:

Preferences.userNodeForPackage(Centrale.class).put("myValue", myString);

I use this code to read it:

String myString = "";
myString = prefs.get("myValue", myString);

I find an error when i save a big string. The error is:

java.lang.IllegalArgumentException: Value too long
java.util.prefs.AbstractPreferences.put(AbstractPreferences.java:245)

How can i solve it?


Solution

  • You would need to break the String into length of Preference.MAX_VALUE_LENGTH. I would suggest that you create myValue.1, myValue.2, etc... That are related to myValue. When loaded you just string the values together.

    Here is some code:

        String value = "....";
        int size = value.length();
        if (size > Preference.MAX_VALUE_LENGTH) {
          cnt = 1;
          for(int idx = 0 ; idx < size ; cnt++) {
             if ((size - idx) > Preference.MAX_VALUE_LENGTH) {
               pref.put(key + "." + cnt, value.substring(idx,idx+Preference.MAX_VALUE_LENGTH);
               idx += Preference.MAX_VALUE_LENGTH;
             } else {
               pref.put(key + "." + cnt, value.substring(idx);
               idx = size;
             }
          }
       } else {
          pref.put(key, value);
       }
    

    There is also a limit on the key size which is Preference.MAX_KEY_LENGTH.

    One more point to make is that you can then use the Preference keys method to recreate your object.