Java Preferences

I would save my object inside .jarwith java preferences.

I convert my object to 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 large string. Error:

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

How can I solve it?

+4
source share
2 answers

You will need to split the String by the length of Preference.MAX_VALUE_LENGTH. I suggest you create myValue.1, myValue.2, etc. This is due to myValue. When loading, you simply group the values ​​together.

Here is the 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 size of the key, which is Preference.MAX_KEY_LENGTH.

, .

+5

, ,

, , Java

if(str.length() > 50) //if the string length > 50
strOut = str.substring(0,50) //return substring from first character to 8 character
strOut2 = str.substring(51, str.length) //second part
+1

Source: https://habr.com/ru/post/1568249/


All Articles