简体   繁体   English

如何在Java中转义“\”字符

[英]How to escape “\” characters in Java

As we all know,we can use 众所周知,我们可以使用

string aa=@"E:\dev_workspace1\AccessCore\WebRoot\DataFile" 

in c# in order not to double the '\\'. 在c#中为了不加倍'\\'。

But how to do in java? 但是在java中该怎么办?

Unfortunately, there is no full-string escape operator in Java. 不幸的是,Java中没有全字符串转义运算符。 You need to write the code as: 您需要将代码编写为:

String aa = "E:\\dev_workspace1\\AccessCore\\WebRoot\\DataFile";

There is no whole string escape operator but, if it's for file access, you can use a forward slash: 没有完整的字符串转义运算符,但是,如果它是用于文件访问,则可以使用正斜杠:

String aa="E:/dev_workspace1/AccessCore/WebRoot/DataFile";

Windows allows both forward and backward slashes as a path separator. Windows允许向前和向后斜杠作为路径分隔符。 It won't work if you pass the path to an external program that mangles with it and fails, but that's pretty rare. 如果你将路径传递给一个随之破坏并失败的外部程序,它将无法工作,但这种情况非常罕见。

Might not be a direct answer to your question, but I feel this should be pointed out: 可能不是你问题的直接答案,但我觉得应该指出:

There's a system-dependent default name-separator character . 有一个依赖于系统的默认名称分隔符

The really system-independent way is to do this: 真正与系统无关的方法是这样做:

String aa = "E:/dev_workspace1/AccessCore/WebRoot/DataFile";
String output = aa.replace('/', File.separatorChar);

It will give you "E:\\dev_workspace1\\AccessCore\\WebRoot\\DataFile" on Windows and "E:/dev_workspace1/AccessCore/WebRoot/DataFile" just about everywhere else. 它将在Windows上提供“E:\\ dev_workspace1 \\ AccessCore \\ WebRoot \\ DataFile” ,并在其他任何地方提供“E:/ dev_workspace1 / AccessCore / WebRoot / DataFile”

If you write a path, you should use the '/' as path-separator under Java. 如果编写路径,则应在Java下使用“/”作为路径分隔符。 The '/' is the official path-separator under Java and will be converted to the appropriate separator for the platform (\\ under windows, / under unix). '/'是Java下的官方路径分隔符,将被转换为平台的适当分隔符(\\ windows下的\\,unix下的/)。 The rest of the string is unchanged if passed to the system, so the '\\' also works under windows. 如果传递给系统,字符串的其余部分将保持不变,因此'\\'也可以在Windows下工作。 But the correct way to represent this path is "E:/dev_workspace1/AccessCore/WebRoot/DataFile". 但表示此路径的正确方法是“E:/ dev_workspace1 / AccessCore / WebRoot / DataFile”。

If you want to represent a '\\' in a Java-String you have to escape it with another one: "This String contains a \\". 如果要在Java-String中表示'\\',则必须使用另一个转义它:“此字符串包含\\”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM