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.

HtmlEscapeTest.java

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
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);
		System.out.println(results);

	}

}

Here is the input.txt file that was used.

input.txt

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

The output of HtmlEscapeTest is shown below.

Results

&lt;sometext&gt;
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.
&lt;/sometext&gt;