15

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?

4
  • 1
    Are there any downsides to just using forward-slashes? Commented Apr 29, 2014 at 11:23
  • 1
    What do you mean by "take" the unescaped path? This is just in source code, after all - if you have user input, you won't need to escape it. Commented Apr 29, 2014 at 11:23
  • Andrei's answer regarding System.getProperty("file.separator"); deals with a lot of the system dependant problems you're going to suffer if you go down this path (but not all). Is there a particular reason you want to lock your program to windows? Personally I would put all your user files within their home directory, which you can get the directory of without any system specific code Commented Apr 29, 2014 at 11:30
  • 1
    JAVA accepts forward slash / as cross platform file separator. So, it is safe to use on Windows platform too. Commented Apr 29, 2014 at 11:31

1 Answer 1

21
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.

Sign up to request clarification or add additional context in comments.

3 Comments

This code will work fine. But is this code really needed? You need to escape the back-slashes only when you are hardcoding the path. And if you are hardcoding, then anyways you need to manually encode the "\"...
I don't know the use-case of the user. Maybe he is reading those paths from a file that a client can modify.
By the way, if you use replaceAll instead of replace, it will give you an error. Check the reason and solution (replaceAll("\\\\", "\\\\\\\\")) [here][link]: [link][stackoverflow.com/questions/1701839/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.