Question

How do i replace the directory path of a string? The original string is:

String fn = "/foo/bar/ness/foo-bar/nessbar.txt";

i need the output to look like:

/media/Transcend/foo-bar/nessbar.txt

I've tried the line below but it doesn't work

fn.replaceAll("/foo/bar/ness", "/media/Transcend");
Was it helpful?

Solution

You forget to rewrite variable:

String fn = "/foo/bar/ness/foo-bar/nessbar.txt";
fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");

OTHER TIPS

Try this:

fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");

The replaceAll method returns a new String object, leaving the original object unmodified. That's why you need to assign the result somewhere, for example, in the same variable.

replaceAll somehow did not work for me, could not figure out why, i ended up something like this, though it replaces only first part of path.

String fn = "C:/foo/bar/ness/foo-bar/nessbar.txt";
Strign r = "C:/foo/bar/ness";
fn = "C:/media/Transcend" + fn.substring(r.length());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top