I am trying to escape forward slash in String which can be used in path using Java.
For example: String:: "Test/World"
Now I want to use above string path.At the same time I have to make sure that "Test/World"
will come as it is in path. Sorry if its duplicate but I couldn't find any satisfactory solution for this.
My purpose is to use above string to create nodes in Zookeeper.
Example:
If I use following string to create node in Zokkeeper then I should get "Test/World" as a single node not separate. Zookeeper accepts "/" as path separator which in some cases I dont require.
/zookeeper/HellowWorld/Test/World
Thanks
Use a double backslash ( \\ ) to denote an escaped string literal.
Special characters can serve different functions in the query syntax. To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"
In java, use this: str = str. replace("\\", "/"); Note that the regex version of replace, ie replaceAll() , is not required here; replace() still replaces all occurrences of the search term, but it searches for literal Strings, not regex matches.
The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.
You should know about File.separator
... This is safer than \
or /
because Linux and Windows use different file separators. Using File.separator
will make your program run regardless of the platform it is being run on, after all, that is the point of the JVM. -- forward slash will work, however, File.separator
will make you end users more confident that it will.
And you don't need to escape "/
... you should also see the answer to this question
String fileP = "Test" + File.separator + "World";
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