1

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");
alvas
  • 115,346
  • 109
  • 446
  • 738
  • Don't use `replaceAll` if you are not going to use regular expressions, use `replace` which does the same job. But for this problem you just might end up doing `File` objects instead of string manipulation.. – dacwe Jan 29 '12 at 17:44
  • @Tom, you do know that this question is much older than the one you've linked as duplicate, right? – alvas Dec 29 '16 at 14:51
  • @alvas And you do know that this isn't important? – Tom Dec 29 '16 at 15:56

3 Answers3

3

You forget to rewrite variable:

String fn = "/foo/bar/ness/foo-bar/nessbar.txt";
fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");
msi
  • 2,609
  • 18
  • 20
1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

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());
MoneyPot
  • 23
  • 7