Search code examples
javareplaceall

String.replaceAll(...) of Java not working for \\ and \


I want to convert the directory path from:

C:\Users\Host\Desktop\picture.jpg

to

C:\\Users\\Host\\Desktop\\picture.jpg

I am using replaceAll() function and other replace functions but they do not work.

How can I do this?

I have printed the statement , it gives me the one which i wanted ie C:\Users\Host\Desktop\picture.jpg but now when i pass this variable to open the file, i get this exception why?

java.io.FileNotFoundException: C:\Users\Host\Desktop\picture.jpg


Solution

  • You have to use :

    String t2 = t1.replaceAll("\\\\", "\\\\\\\\");
    

    or (without pattern) :

    String t2 = t1.replace("\\", "\\\\");
    

    Each "\" has to be preceeded by an other "\". But it's also true for the preceeding "\" so you have to write four backslashes each time you want one in regex.