-5

I am getting my browse file location from withing the system , so the generated string path is as

String path = "C:\Documents and Settings\abcd\Desktop\d.txt";

My input is coming from browse button , so input file path is dynamic. I need to Replacing backward slash '\' to foward slash '/' , so that i could use the path further in my coding . I need to do this dynamically . Can anybody tell me how.

My desired output is

C:/Documents and Settings/abcd/Desktop/d.txt

Thanks in advance.

Correct Answer ---

Following is the correct answer for the above mentioned question --- String newPath = path.replaceAll("\\", "/");

NewBee
  • 839
  • 7
  • 18
  • 42
  • 5
    What did you try? What are you having trouble with? – SLaks May 30 '13 at 14:03
  • 1
    If you are getting the path dynamically, you don't need to replace the backslash. If your String is a literal like you have, it will produce a compilation error. – Sotirios Delimanolis May 30 '13 at 14:05
  • 1
    I am getting my path dynamically as mentioned above, which is producing error if used again to locate the file. – NewBee May 31 '13 at 04:16

2 Answers2

2

You can use replaceAll to replace a substring in a string :

String path = "C:\Documents and Settings\abcd\Desktop\d.txt";
String goodPath = path.replaceAll("\\", "/");
Magus
  • 14,796
  • 3
  • 36
  • 51
1

The first statement will not compile without escaping the backslash characters. The backslash character is used to denote the beginning of a control character or unicode literal so must be escaped to represent the \ literal value itself.

You can do

String path = "C:\\Documents and Settings\\abcd\\Desktop\\d.txt";
String newPath = path.replace("\\", "/");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Ignoring that this is a dup ... s/replace/replaceAll/ – Brian Roach May 30 '13 at 14:07
  • From the [javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) for replace _Returns a new string resulting from replacing **all** occurrences of oldChar in this string with newChar._ – Reimeus May 30 '13 at 14:10
  • @BrianRoach: `replaceAll` takes a regex. – SLaks May 30 '13 at 14:40
  • Can u eleborate as how are u changing String path = "C:\Documents and Settings\abcd\Desktop\d.txt" to "C:\\Documents and Settings\\abcd\\Desktop\\d.txt". – NewBee May 31 '13 at 04:08
  • You mean why? - sure `\\`` is used is denote the beginning of the control character so you you need to escape it in a `String`. – Reimeus May 31 '13 at 12:32