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


The escapeJava() method of the StringEscapeUtils class in the Commons LangS library can be used to insert JavaSW escape characters into a String. It takes the String to escape as a parameter and returns the String with Java escape characters inserted.

The JavaEscapeTest class gives an example of this. It reads in the input.txt file as a String (using FileUtils from Commons IO). It passes this String to StringEscapeUtils.escapeJava() and displays the escaped results to the console.

JavaEscapeTest.java

package test;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;

public class JavaEscapeTest {

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

		String str = FileUtils.readFileToString(new File("input.txt"));
		String results = StringEscapeUtils.escapeJava(str);
		System.out.println(results);

	}

}

The input.txt file is shown here.

input.txt

	Here is some "Text" that
I'd like to be "escaped" for Java.
I'll try a couple special characters here: \ "

The results of JavaEscapeTest are shown below.

Results

\tHere is some \"Text\" that\r\nI'd like to be \"escaped\" for Java.\r\nI'll try a couple special characters here: \\ \"