Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Emanuel
4 years ago

Or without library:
replaceAll(“\\\\n”, System.lineSeparator())

Thomas
9 years ago

I just found out that wrapping the new line character with simple quotes (like this ‘n’) works too.

Markus
11 years ago

Thanks mykong,

that was exact what I was looking for.
Needed it for a little project with spring, where I want to configer a nw line character (\n or \cr or \r\n) in a spring bean.

Regards
Markus

Jon
11 years ago
Would this work also?

hello = Hi \
   \
   Good Morning \
   \
   thanks