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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With