How to escape “\” characters in Java

后端 未结 5 442
说谎
说谎 2020-12-11 06:31

As we all know,we can use

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

in c# in order not to double the \'\\\'.

相关标签:
5条回答
  • 2020-12-11 07:14

    If you write a path, you should use the '/' as path-separator under Java. The '/' is the official path-separator under Java and will be converted to the appropriate separator for the platform (\ under windows, / under unix). The rest of the string is unchanged if passed to the system, so the '\' also works under windows. But the correct way to represent this path is "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 \".

    0 讨论(0)
  • 2020-12-11 07:20

    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.

    0 讨论(0)
  • 2020-12-11 07:22

    Unfortunately, there is no full-string escape operator in Java. You need to write the code as:

    String aa = "E:\\dev_workspace1\\AccessCore\\WebRoot\\DataFile";
    
    0 讨论(0)
  • 2020-12-11 07:23

    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. It won't work if you pass the path to an external program that mangles with it and fails, but that's pretty rare.

    0 讨论(0)
  • 2020-12-11 07:26

    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.

    0 讨论(0)
提交回复
热议问题