Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (7k points)

I have generated a file name and stored it in a String variable path have tried using

path=path.replaceAll(‘\’,’,’)

But it is not working. Can someone help me with this?

1 Answer

0 votes
by (13.1k points)

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 first String is a regular expression. So, writing it as a RegEx:

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

Is what you were looking for.

To make optimal your core, you should make it independent of the Operating System:

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

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

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

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...