-1

In Netbeans I am using a JFileChooser to get a file's path. All is OK and its giving me the path as well with single slash \. But I need the path with double slash \\. So my question is, is there already any kind of method which can provide me that type of path? I also don't know the name of the path which has double slash \\. Example- H:\\New folder\\odesk\\odeskViolin4.wav What can I do now?

Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49

2 Answers2

2

You can simply replace the \ symbols with \\, by using the String.replaceAll() method.

String input = "C:\\Users\\myName"; //special characters have to be escaped.
String doubleSlashed = input.replaceAll("\\\\", "\\\\\\\\");
System.out.println(doubleSlashed);

This will print:

C:\\Users\\myName

Note that String.replaceAll(String pattern, String replacement) takes two arguments and in my example they are four-slashed and eight-slashed strings. This is because the \ symbol is a special character and has to be escaped.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • 1
    Does your solution actually run for you? I get `java.util.regex.PatternSyntaxException: Unexpected internal error near index 1` when I try. [EDIT: Found a solution, you have to use `input.replaceAll("\\\\", "\\\\\\\\");`](http://stackoverflow.com/questions/1701839/backslash-problem-with-string-replaceall) – Supericy May 27 '13 at 02:03
  • 1
    Not the down voter, but this seems a *very* odd requirement. Better to wait for the answer to @Mad's question before rushing in. – Andrew Thompson May 27 '13 at 02:03
  • @kocko I am having a error `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException` – Tushar Monirul May 27 '13 at 02:06
1

Assuming you truly want to replace single backslashes with double backslashes, you could simply do this:

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

However, you may not actually want double backslashes, depending on your purpose. You should at least be aware of this:

String oneBackSlash   = "\\";    //This String will consist of one backslash
String twoBackSlashes = "\\\\";  //This String will consist of two backslashes
//The String below has no double backslashes, only single ones
String path = "H:\\New folder\\odesk\\odeskViolin4.wav";

System.out.println(oneBackSlash);
System.out.println(twoBackSlashes);
System.out.println(path);

Output:

\
\\
H:\New folder\odesk\odeskViolin4.wav
Lone nebula
  • 4,768
  • 2
  • 16
  • 16