How do I escape a String for HTML?
Author: Deron Eriksson
Description: This Java example shows how to escape a String for HTML using StringEscapeUtils.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The escapeHtml() method of the StringEscapeUtils class in the Commons LangS library can be used to convert a String to its HTMLW entity representation. As an example, this would convert an ampersand (&) in a String to its HTML entity equivalent (&).

The HtmlEscapeTest class demonstrates this. It reads a String of text from the input.txt file (using FileUtils from Commons IOS) and substitutes HTML entities using the StringEscapeUtils.escapeHtml() method. It outputs the resulting String to the console.

package test;


import org.apache.commons.lang.StringEscapeUtils;

public class HtmlEscapeTest {

	public static void main(String[] args) throws Exception {

		String str = FileUtils.readFileToString(new File("input.txt"));
		String results = StringEscapeUtils.escapeHtml(str);



Here is the input.txt file that was used.


Here is some "Text" that I'd like to be "escaped" for HTML
& here is some Swedish: Tack. Vars?god.

The output of HtmlEscapeTest is shown below.


Here is some &quot;Text&quot; that I'd like to be &quot;escaped&quot; for HTML
&amp; here is some Swedish: Tack. Vars&aring;god.