How to Iterate Through Values in Properties File in Java
so I was wondering if anyone knew how I would go about reading in mutliple values from a key, delimiting them by commas and storing them to an arraylist from a properties file in java?
I have a properties file with just this in it:
currentProposalsLocation = C:/Documents and Settings/Intern Project/Extracted Items
keywordsList = "A,B,C,D,E,F"
And this is my code to load the properties file:
static String proposalsDirectory;
sta开发者_JS百科tic ArrayList<String> keywordsList = new ArrayList<String>();
private static final String PROP_FILE="C:/Documents and Settings/Intern Project/ipConfig.properties";
public static void readPropertiesFile()
{
try
{
InputStream is = XMLTagParser.class.getResourceAsStream(PROP_FILE);
Properties prop = new Properties();
prop.load(is);
proposalsDirectory = prop.getProperty("currentProposalsLocation");
//?????What to do here????
is.close();
}
catch(Exception e)
{
System.out.println("Failed to read from " + PROP_FILE + " file.");
}
}
If anyone could help me out, I'd really appreciate it.
keywordsList.addAll(Arrays.asList(prop.getProperty("keywordsList").split(","));
Should work.
Properties
extends HashTable
implements Map
, so you can get all the keys as a Set<String>
using keySet()
.
Any property value is a String. You can split the String given a delimiter.
If you're asking how to add that Object back into the Properties, the answer is "you can't". Properties uses a String key and a String value. If you want multi-map behavior (String key, List value), you'll have to implement your own.
Use an Enumerator to cycle through Properties
Just to add another option, you could set the properties up in an XML file, use Spring Dependency Injection to load them into an object within your java code, and then manipulate them however you please.
Note with Dependency Injection, you could set that list up directly in the XML as a List so you wouldn't even have to do all the busy work of turning a comma separated String into a List.
精彩评论