37

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sameek Mishra
  • 9,174
  • 31
  • 92
  • 118

4 Answers4

68

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
12

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('\\', '/');
Raze
  • 2,175
  • 14
  • 30
8

If you have:

String s = "c:\\upload\\date\\csv\\sample.csv";

In Java, you can just use:

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

Which will make s equal to:

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

Paul
  • 139,544
  • 27
  • 275
  • 264
0

For double back slash ("\\")

For Java you can use string.replaceAll("\\\\","/")

&

For Kotlin you can use string.replace("\\\\".toRegex(),"/")