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?
views:
240answers:
4Using:
\\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.
Given String s
,
s = s.replace("\\", "\\\\");
Replaces all \
with \\
.
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.