Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array in properties file (ClassCastException error)

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
0
0
CA
Hi,

I have a "config.properties" file that I use to lookup configuration properties for my app.

Code:
//CONFIG_PROPERTY_FILE is constant equivalent to "config"
PropertyResourceBundle configVars = (PropertyResourceBundle)PropertyResourceBundle.getBundle(CONFIG_PROPERTY_FILE,Locale.ENGLISH);
//get key values like this
String myKeyValue = configVars.getString("key");

However, I want to have several pairs with the same key name, so that i could call the getStringArray() function. I'm thinking something like this:

Code:
import java.io.*;
import java.lang.*;
import java.util.*;

public class Test{
    
    //main function
    public static void main (String args[]) {
           
           PropertyResourceBundle configVars = (PropertyResourceBundle)PropertyResourceBundle.getBundle("config",Locale.ENGLISH);
           String[] arr = configVars.getStringArray("key");
           
           for (int ctr=0;ctr<arr.length;ctr++)
           {
               System.out.println(arr[ctr]);
           }
           
    }//end main
 
}//end class

Code:
#contents of config.properties
key = first value
key = second value
key = third value

When I try this, I get
Code:
Exception in thread "main" java.lang.ClassCastException
        at java.util.ResourceBundle.getStringArray(ResourceBundle.java:291)
        at Test.main(Test.java:17)

Any suggestions? Much appreciated!!
 
What is happening is that the Object returned by getStringArray is not an array of Strings.

I'd try to use the getObject() method and look what's actually returning.

Cheers.

Dian
 
Properties files can't have more than one key with the same name. End of story.

You can't define a string array in a properties resource bundle. YOu need to create a new implementation of resourcebundle that binds a string array to your given key.
 
Have you had a look at [tt]java.util.ListResourceBundle[/tt]? It's accessed just like a [tt]PropertyResourceBundle[/tt] except that the key/values are stored in your class (which would extend ListResourceBundle) and the values can be objects. You would still only have one key but the value could be an array of values!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top