Escape Special Characters in String Using Java Library

We can use Apache's commons-text library to escape the special characters in HTML entities. Before moving further, we will first understand what are special characters and what does escaping of special characters mean.

What are Special Characters?

Below is the list of special characters:

&
>
< 
"

Read Also: Escape Sequences in Java

What does Escaping of Special Characters mean?

Escaping of Special characters means replacing them with HTML character-entities. For example:

Symbol HTML Entities Name
&
&amp;
>
&gt;
<
&lt;
"
&quot;

Add Dependency:

Add the below dependency to your pom.xml. The below dependency can be used with Java8+. You can check the latest version here.

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

We will use StringEscapeUtils.escapeHtml4() method to escape special characters in String.

Note: Use org.apache.commons.text.StringEscapeUtils instead of org.apache.commons.lang3.StringEscapeUtils because later class is deprecated.

Java Program:

Below is the Java Program for escaping special characters in String using commons-text java library.

import org.apache.commons.text.StringEscapeUtils;

public class JavaHungry {
    public static void main(String args[]) {
        // Given special character
     String testString = " <   >   &   \" ";
     // Escape special character using StringEscapeUtils class
     String outputString = StringEscapeUtils.escapeHtml4(testString);
     // Printing the output
  System.out.println("Special Characters : "+ testString +"\n Escaped Output : "+outputString);
    }
}

Output:
Special Characters :  <   >   &   " 
Escaped Output :  &lt;   &gt;   &amp;   &quot;

That's all for today, please mention in the comments in case you have any queries regarding escaping special characters in String using the commons-text Java library.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry