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 |
&
|
& |
>
|
> |
<
|
< |
"
|
"
|
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 : < > & "
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.