escaping backslash in java string literal

72,908
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.

Share:
72,908
Eypros
Author by

Eypros

Updated on July 11, 2022

Comments

  • Eypros
    Eypros almost 2 years

    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?