I'm looking for a smart Java String formatter similar to the standard Formatter:
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer);
formatter.format("hello %1$s, %2$s and %3$s", "me", "myself", "I");
The problem is that if you make a mistake in the format (e.g. you forget the $s
) an exception will be thrown. Not really what I want when formatting an error message (since it's not in the regular path of the application and may not be tested).
I could of course define my own class, let's say accept a string like "hello $1, $2 and $3
, do the replacement with ($1
-> %1$s
) and invoke the toString()
for all parameters but I'm sure a better solution has been already developed.
Somewhere, in some jar...
Thanks for any useful pointer.
EDIT
I'm looking for something that like the following:
String out = MySpecialFormatter.format("hello $1, $2 and $3", "me", "myself", "I");
if you have an error in your format (well, typos exist), it tries its best to fill in the bind variables, or return the original format string.