Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace backslash with forward slash [duplicate]

Tags:

java

regex

file

I have the following path: com/teama/merc/test/resTest And I want to convert it to this: com\teama\merc\test\resTest

I am trying to append the above path to this path: C:\Users\Toby\git\MERCury\MERCury\ With str.replace('/', '\\'); But when I append both of the strings together, this is the output: C:\Users\Toby\git\MERCury\MERCury\com/teama/merc/test/resTest

Here is the code in question:

    String home = System.getProperty("user.dir");
    path.replace('/', '\\');
    System.out.println(path);

    String folder = home + File.separatorChar + path;
    System.out.println(folder);

    File file = new File(folder);
    if(file.isDirectory())
    {
        System.out.println(file.getPath() + " is a directory");
    }

The appended path is not seen as a folder because of the slashes. Any help?

Edit: Just to clarify, the full path (both strings appended) is infact a folder.

like image 258
user3316633 Avatar asked Feb 13 '23 13:02

user3316633


1 Answers

In java, String's aren't mutable, so when you change them with something like the replace method, you have to reassign the variable to that changed String. So, you would have to change the replace code to this:

path = path.replace('/', '\\');
like image 191
kabb Avatar answered Feb 16 '23 02:02

kabb