escaping backslash in java string literal

Eypros picture Eypros · Apr 29, 2014 · Viewed 66k times · Source

I am using Java for a while and come up with this problem: I use hard-coded paths in windows like

"D:\Java-code\JavaProjects\workspace\eypros\src"

The problem is that I need to escape the backslash character in order to use it with string. So I manually escape each backslash:

"D:\\Java-code\\JavaProjects\\workspace\\eypros\\src"

Is there a way to automatically take the unescaped path and return an escaped java string.

I am thinking that maybe another container besides java string could do the trick (but I don't know any).

Any suggestions?

Answer

Andrei picture Andrei · Apr 29, 2014
public static String escapePath(String path)
{
    return path.replace("\\", "\\\\");
}

The \ is doubled since it must be escaped in those strings also.

Anyway, I think you should use System.getProperty("file.separator"); instead of \.

Also the java.io.File has a few methods useful for file-system paths.