How to insert a new line in resource bundle messages – java
Here is a simple ResourceBundle message files
hello = "Hi \n \n Good Morning \n \n thanks"
If we retrieve the resource bundle key “hello”, we expected the result as following
Hi Good Morning thanks
Unfortunately, Java doesn’t work in this way, “String” will not translate the \n into new line by default. If we retrieve the “hello” from resource bundle directly, we will get the following result. This is not what we want ….
Hi \n \n Good Morning \n \n thanks
Solution
What we need to do is translate the “\n” into a new line in Java. StringEscapeUtils is a handy class to handle this issue. We can use the StringEscapeUtils.unescapeJava(String str) method to translate the “\n” into a new line.
StringEscapeUtils.unescapeJava(String str) definition
String org.apache.commons.lang.StringEscapeUtils.unescapeJava(String str)
Unescapes any Java literals found in the String. For example, it will turn a sequence of ‘\’ and ‘n’ into a newline character, unless the ‘\’ is preceded by another ‘\’.
Parameters:
str the String to unescape, may be null
Reference
http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html