Take the 2-minute tour ×

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?

share|improve this question
Could you post you current code for reading and outputting? –  helios Mar 9 '10 at 1:54
How are you reading in the source file? And how exactly are you printing them? From your description it's not obvious to me where the escape sequences are getting converted into the escape characters that they represent. –  Nate C-K Mar 9 '10 at 1:55
add comment

4 Answers

up vote 6 down vote accepted

You should use the StringEscapeUtils library from the well-known Apache Commons. 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(). There are plenty of other escaping utilities in that library as well.


share|improve this answer
add comment

Given String s,

s = s.replace("\\", "\\\\");

Replaces all \ with \\.

share|improve this answer
add comment


\\n and \\t

Some characters preceded by a backslash (\) form an escape sequence and have special meaning to the compiler. So in your case \n and \t are treated as special (newline and tab respectively). So we need to escape the backslash to make n and t treated literally.

share|improve this answer
The file I'm reading contains \n, and I would like to programmatically convert that to \\n –  Marius Mar 9 '10 at 2:07
add comment

StringEscapeUtils is good for string related operations

share|improve this answer
add comment

Your Answer


