user3253955
user3253955

Reputation: 443

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?

Upvotes: 5

Views: 1736

Answers (2)

Claudio Corsi
Claudio Corsi

Reputation: 359

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.

Upvotes: 9

Uriel Salischiker
Uriel Salischiker

Reputation: 21

You could cut your String in parts as the exception is saying that your String is too long

An example in how to split a string at certain character count can be found at Cut Java String at a number of character

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

Upvotes: 1

Related Questions