In my properties file I have one property, which contains a comma separated list of values
In my code, I would like to load that property in, split it from the commas, and add each value into an array. I also want to make sure I don't have values in the array due to whitespace etc
example property :
prop_allowed_extensions = .jpeg,tiff, .txt
I have come up with this so far, but it feels dirty, is there a more elegant solution?
String test = classProperties.getProperty("prop_allowed_extensions", "txt, jpeg");
String[] splitString = StringUtils.split(test, ',');
String[] newString = new String[splitString.length];
for (int i = 0; i < splitString.length; i++)
{
newString[i] = StringUtils.trim(splitString[i]);
}
I just want the text of the file extension, would it be appropriate to use a regular expression to remove whitespace/non-letters?
Apache Jakarta Commons Configuration handles properties file in a clean way, allowing you to specify lists in different formats:
colors.pie = #FF0000, #00FF00, #0000FF
OR
colors.pie = #FF0000;
colors.pie = #00FF00;
colors.pie = #0000FF;
And get the list like this:
String[] colors = config.getStringArray("colors.pie");
List colorList = config.getList("colors.pie");
See the How-to
You can do it in two steps:
String[] allowedExtensions = str.replaceAll("[^\\w,_]", "").split(",")
(First kill anything that is not either a comma, an underscore or a word character (letter or digit), then split the resulting string
I'd personally just reduce it to the following (keeping in mind that String.split()
takes a regular expression), but I don't know whether or not you'd consider it more elegant:
String test = classProperties.getProperty("prop_allowed_extensions",
"txt, jpeg");
String[] extensions = test.trim().split("\\s*,\\s*");
Edit: You can remove the leading dot on each extension too, if it is present (this, or one of several other ways):
String[] test = classProperties.getProperty("prop_allowed_extensions",
"txt, jpeg").trim().split("^\\.", 2);
String[] extensions = test[test.length - 1].split("\\s*,\\s*.?");
Following your pattern, you can do it like this:
String test = classProperties.getProperty("prop_allowed_extensions", "txt, jpeg");
List<String> extensions = new ArrayList<String>();
for (String part:test.split(",")) {
extensions.add(part.trim());
}
The difference is that the result is in a list now. test.split(",")
will be called only once, so there is no performance issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With