Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a string in Java?

I'm reading a sourcefile in Java, but when I print it (sysout), the escaped characters are no longer escaped. How can I escape characters like \n and \t in a string in Java?

like image 812
Marius Avatar asked Mar 09 '10 01:03

Marius


2 Answers

You should use the StringEscapeUtils class from Apache Commons Text (you can also find the class in Apache Commons Lang3 but that one is deprecated). You'll find that there are plenty of other offerings in Apache Commons that might serve useful for other problems you have in Java development, so that you don't reinvent the wheel.

The specific call you want has to do with "Java escaping"; the API call is StringEscapeUtils.escapeJava(). For example:

System.out.println(StringEscapeUtils.escapeJava("Hello\r\n\tW\"o\"rld\n")); 

would print out:

Hello\r\n\tW\"o\"rld\n 

There are plenty of other escaping utilities in that library as well. You can find Apache Commons Text in Maven Central and you'd add it to your Maven project like this:

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

and in case you are using Gradle:

compile "org.apache.commons:commons-text:1.3" 
like image 59
schematic Avatar answered Sep 21 '22 11:09

schematic


Many of the solutions here suggest adding the Apache Commons Text and using StringEscapeUtils. Some of the other solutions here are simply wrong.

A potential solutions is as follows:

/**  * escape()  *  * Escape a give String to make it safe to be printed or stored.  *  * @param s The input String.  * @return The output String.  **/ public static String escape(String s){   return s.replace("\\", "\\\\")           .replace("\t", "\\t")           .replace("\b", "\\b")           .replace("\n", "\\n")           .replace("\r", "\\r")           .replace("\f", "\\f")           .replace("\'", "\\'")           .replace("\"", "\\\""); } 

The escape list is from Oracle's list. (Note that \\ is escaped first as you don't want to re-escape it later.)

This solution isn't as fast as it could be, but it should work. Ideally you would only parse the String once and you wouldn't need to keep rebuilding your String array. For small Strings this should be fine.

If you're thinking about this from the perspective of storing data, also consider something like converting it to Base64 representation - it's fast, single parse and uses not too much extra space.

like image 41
Dan Avatar answered Sep 20 '22 11:09

Dan