Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape "\" characters in Java

Tags:

java

c#

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?

like image 764
Edwin Tai Avatar asked Jul 23 '09 05:07

Edwin Tai


People also ask

How do you escape an escape character in Java?

So in a character literal, you need to escape single quotes, e.g. '\'' . So all you need is "\\'" , escaping only the backslash.

How do you escape characters?

Use the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.

What do \n and \t do in Java?

These are escape characters which are used to manipulate string. \t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point.

How do you escape a string in Java?

However, we know that the backslash character is an escape character in Java String literals as well. Therefore, we need to double the backslash character when using it to precede any character (including the \ character itself).


4 Answers

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";
like image 103
notnoop Avatar answered Oct 21 '22 00:10

notnoop


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.

like image 21
Vinko Vrsalovic Avatar answered Oct 21 '22 00:10

Vinko Vrsalovic


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.

like image 4
Flo Avatar answered Oct 20 '22 23:10

Flo


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.

like image 3
Robert Petermeier Avatar answered Oct 21 '22 01:10

Robert Petermeier