在java字符串文字中转义反斜杠 [英] escaping backslash in java string literal
问题描述
我在Windows中使用硬编码路径,如
D:\Java-code\JavaProjects\workspace\eypros\src
问题是我需要转义反斜杠字符才能使用字符串。所以我手动转义每个反斜杠:
D:\\\Java-code\\JavaProjects\\ workspace \\eypros\\src
有没有办法自动将未转义路径并返回一个转义的java字符串。
我想,除了java字符串之外,可能还有一个容器可以做到这一点(但我不知道)。
任何建议?
public static String escapePath(String path)
{
return path.replace(\\,\\\\\);
}
\
因为它也必须在那些字符串中被转义。
无论如何,我想你应该使用 System.getProperty(file.separator) ;
而不是 \
。
另外, java .io.File
有一些对文件系统路径有用的方法。
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?
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.
这篇关于在java字符串文字中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!