Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping backslash in java string literal [duplicate]

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?

like image 316
Eypros Avatar asked Apr 29 '14 11:04

Eypros


People also ask

What is the use of \\ in Java?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

What does 2 backslashes mean in Java?

Mango \\ Nightangle is the encoded form, the double backslash being an escape sequence where Java expects a special character. Because of this a single backslash would lead to a compilation error.

How do you replace a backslash on a string?

To replace all backslashes in a string:Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.


1 Answers

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.

like image 183
Andrei Avatar answered Sep 24 '22 09:09

Andrei