Edwin Tai
Edwin Tai

Reputation: 1234

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

But how to do in java?

Upvotes: 5

Views: 6267

Answers (5)

Mnementh
Mnementh

Reputation: 51311

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

Upvotes: 1

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340211

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.

Upvotes: 12

Robert Petermeier
Robert Petermeier

Reputation: 4152

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.

Upvotes: 3

Flo
Flo

Reputation: 2778

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.

Upvotes: 4

notnoop
notnoop

Reputation: 59299

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

Upvotes: 20

Related Questions