I'm loading a file of Java properties which looks like:
transfer_detail = Transfer {0} from {1} to {2} on {3}
After parsing that property I should have String that looks like:
Trans开发者_运维知识库fer 200.30 from Debit Account to Credit Account on 2011/01/26
I implemented my self a parser which looks like:
// simplified for brevity
private static String translate(String string, String... replacements){
String result = string;
for(int i = 0; i < replacements.length; i++){
result = result.replace("{"+i+"}", replacements[i]);
}
return result;
}
// and I use it this way:
String result = translate("transaction", "200.30", "Debit Account", etc...);
What I've been wondering is if there's something to do so in the J2SE API. Even for simple things like this I don't like to reinvent the wheel. Do you know any other easier or cleaner way to achieve this?
You want to use the MessageFormat
class for filling in the placeholders with actual values.
Don't do that... it's yucky. :)
Use MessageFormat instead.
MessageFormat form = new MessageFormat("Transfer {0} from {1} to {2} on {3}");
System.out.println(form.format(new String[] {
"200.30",
"Debit Account",
"Credit Account",
"2011/01/26"
}));
API MessageFormat doesn't work with messages containing quotes.
You have to manually do the job by using regex for example.
精彩评论