javastringreplacestringescapeutils

Replace directory path by manipulating string - Java


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");

Solution

  • You forget to rewrite variable:

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