Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace backward slash to forward slash using java?

Tags:

java

regex

I'm importing a CSV file to MySQL database. This can be done using java.mysql support for forward slash in file path. If user gives the path

c:\upload\date\csv\sample.csv 

MySQL doesn't support this type of path pattern. I want to search for backslashes in the path and replace them with a forward slash, to give this:

  c:/upload/date/csv/sample.csv 

How is that done?

like image 644
Sameek Mishra Avatar asked Jul 24 '11 05:07

Sameek Mishra


People also ask

How do you change backslash to forward slash?

Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

How do you remove the backward slash in Java?

str = str. replace("\\", ""); replaceAll() treats the first argument as a regex, so you have to double escape the backslash. replace() treats it as a literal string, so you only have to escape it once.

How do you replace a single slash in Java?

Replacing a Single Backslash( \ ) With a Double Backslash( \\ ) Using the replaceAll() Method. This is another solution that you can use to replace the backslashes. Here, we used the replaceAll() method that works fine and returns a new String object.


2 Answers

In java, use this:

str = str.replace("\\", "/"); 

Note that the regex version of replace, ie replaceAll(), is not required here; replace() still replaces all occurrences of the search term, but it searches for literal Strings, not regex matches.

like image 82
Bohemian Avatar answered Sep 21 '22 21:09

Bohemian


The String.replace(CharSequence, CharSequence) example provided by @PaulPRO and @Bohemian will work, but its better to use the String.replace(char, char) version. Slightly faster. Though you won't have a noticeable speed difference, its better to do such optimisations where possible.

String replacedStr = str.replace('\\', '/'); 
like image 40
Raze Avatar answered Sep 20 '22 21:09

Raze