escaping backslash in java string literal [duplicate]

这一生的挚爱 提交于 2019-11-30 03:42:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23363241/escaping-backslash-in-java-string-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!