Replace directory path by manipulating string - Java [duplicate]
-
20-04-2021 - |
Frage
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");
Lösung
You forget to rewrite variable:
String fn = "/foo/bar/ness/foo-bar/nessbar.txt";
fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");
Andere Tipps
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());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow