Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape forward slash in java so that to use it in path

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

like image 643
Frank Avatar asked Jul 08 '14 23:07

Frank


People also ask

How do you escape the front slash in Java?

Use a double backslash ( \\ ) to denote an escaped string literal.

How do you escape a special character in path?

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

How do I change one forward slash in Java?

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.

How do you escape a slash?

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.


1 Answers

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";
like image 164
J-Dizzle Avatar answered Jan 04 '23 21:01

J-Dizzle