11

I want to change the backslash in a string to double backslash.

I have

String path = "C:\Program Files\Text.txt";

and I want to change it to

"C:\\Program Files\\Text.txt"
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user2060390
  • 157
  • 2
  • 2
  • 5
  • 7
    Doesn't that say syntax error? – Anirudh Ramanathan Feb 23 '13 at 13:37
  • 2
    Always use `/` instead of \\ for file-system paths, since `/` is OS-independent. – Eng.Fouad Feb 23 '13 at 13:46
  • You don't have (1), because it doesn't compile: therefore you don't have the problem of converting it to (2). What you probably have is a string that contains single backslashes, derived not from a literal, but say from the user, which is already usable as it is. The double backslashes are only required for string literals, and they are converted to single by the compiler. You don't have this problem. Not a real question. – user207421 Feb 23 '13 at 22:45

2 Answers2

23

replaceAll is using regex, and since you don't need to use regex here simply use

path = path.replace("\\", "\\\\");

\ is special in String literals. For instance it can be used to

  • create special characters like tab \t, line separators \n \r,
  • or to write characters using notation like \uXXXX (where X is hexadecimal value and XXXX represents position of character in Unicode Table).

To escape it (and create \ character) we need to add another \ before it.
So String literal representing \ character looks like "\\". String representing two \ characters looks like "\\\\".

Pshemo
  • 122,468
  • 25
  • 185
  • 269
9

Using String#replace()

String s= "C:\\Program Files\\Text.text";
System.out.println(s.replace("\\", "\\\\"));
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • I am getting error as "Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1" – user2060390 Feb 23 '13 at 13:40
  • 2
    @user2060390 you are probably using replaceAll. you don't really need a regex solution here just use replace() which expects a string and an replacement string. – PermGenError Feb 23 '13 at 13:42
  • 4
    `System.out.println(s.replaceAll("\\\\", "\\\\\\\\"));` would work if you want to use `replaceAll`. – Bernhard Barker Feb 23 '13 at 13:43
  • If you want to use replaceAll try this: 'System.out.println(s.replaceAll("\\\\", "\\\\\\\\"));' however i strongly recommend to use non-regex String#replace solution in this case. :) – PermGenError Feb 23 '13 at 13:43
  • I am getting the path of the file using "Paths.get(selfile)" and iam passing it as input for "PDDOcument.load(input)". – user2060390 Feb 23 '13 at 15:32
  • replacing the "real backslash" with the "actual backslash, for real this time" http://xkcd.com/1638/ – Conrad Frix Feb 03 '16 at 14:37