How do I escape a string in Java?

You should use the StringEscapeUtils class from Apache Commons Text (you can also find the class in Apache Commons Lang3 but that one is deprecated). You’ll find that there are plenty of other offerings in Apache Commons that might serve useful for other problems you have in Java development, so that you don’t reinvent the wheel.

The specific call you want has to do with “Java escaping”; the API call is StringEscapeUtils.escapeJava(). For example:

System.out.println(StringEscapeUtils.escapeJava("Hello\r\n\tW\"o\"rld\n"));

would print out:

Hello\r\n\tW\"o\"rld\n

There are plenty of other escaping utilities in that library as well. You can find Apache Commons Text in Maven Central and you’d add it to your Maven project like this:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.3</version>
</dependency>

and in case you are using Gradle:

compile "org.apache.commons:commons-text:1.3"

Leave a Comment