在java字符串文字中转义反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23363241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:14:23  来源:igfitidea点击:

escaping backslash in java string literal

javastringescapingbackslash

提问by Eypros

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

我使用 Java 有一段时间了,并提出了这个问题:我在 Windows 中使用硬编码路径,例如

"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.

有没有办法自动采用未转义的路径并返回转义的java字符串。

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

我想也许除了 java string 之外的另一个容器可以解决这个问题(但我不知道)。

Any suggestions?

有什么建议?

回答by Andrei

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 \.

无论如何,我认为你应该使用System.getProperty("file.separator");而不是\.

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

还有java.io.File一些对文件系统路径有用的方法。