Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
user3253955 Avatar asked Dec 19 '14 01:12

user3253955


2 Answers

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.

like image 156
Claudio Corsi Avatar answered Sep 19 '22 09:09

Claudio Corsi


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
like image 40
Uriel Salischiker Avatar answered Sep 20 '22 09:09

Uriel Salischiker