11

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?

Not a bug
  • 4,286
  • 2
  • 40
  • 80
Eypros
  • 5,370
  • 6
  • 42
  • 75
  • 1
    Are there any downsides to just using forward-slashes? – user432 Apr 29 '14 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. – Jon Skeet Apr 29 '14 at 11:23
  • [Andrei's answer](http://stackoverflow.com/a/23363356/2187042) 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 – Richard Tingle Apr 29 '14 at 11:30
  • 1
    JAVA accepts forward slash `/` as cross platform file separator. So, it is safe to use on `Windows` platform too. – Ravinder Reddy Apr 29 '14 at 11:31

1 Answers1

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

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Andrei
  • 3,086
  • 2
  • 19
  • 24
  • 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 "\"... – Hirak Apr 29 '14 at 11:36
  • 1
    I don't know the use-case of the user. Maybe he is reading those paths from a file that a client can modify. – Andrei Apr 29 '14 at 11:41
  • 2
    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][https://stackoverflow.com/questions/1701839/string-replaceall-single-backslashes-with-double-backslashes] – Mashrur Jul 05 '17 at 07:03