Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace ' \' with '/' in a java string [duplicate]

Tags:

java

string

i have generated a file name and stored in a String variable path hav tried using

path=path.replaceAll('\','/') 

but this does not work

like image 674
Francis Avatar asked Oct 31 '12 08:10

Francis


2 Answers

replaceAll() needs Strings as parameters. So, if you write

path = path.replaceAll('\', '/');

it fails because you should have written

path = path.replaceAll("\", "/");

But this also fails because character '\' should be typed '\\'.

path = path.replaceAll("\\", "/");

And this will fail during execution giving you a PatternSyntaxException, because the fisr String is a regular expression (Thanks @Bhavik Shah for pointing it out). So, writing it as a RegEx, as @jlordo gave in his answer:

path = path.replaceAll("\\\\", "/");

Is what you were looking for.

To make optimal your core, you should make it independent of the Operating System, so use @Thai Tran's tip:

path = path.replaceAll("\\\\", File.separator);

But this fails throwing an StringIndexOutOfBoundsException (I don't know why). It works if you use replace() with no regular expressions:

path = path.replace("\\", File.separator);
like image 183
J.A.I.L. Avatar answered Sep 20 '22 17:09

J.A.I.L.


If it is a file path, you should try "File.separator" instead of '\' (in case your application works with Nix platform)

like image 37
Thai Tran Avatar answered Sep 19 '22 17:09

Thai Tran