-2

Hi I want to replace a backslash character \ by double backslash character \\ from a string in Java but the replace() method does not seem to work. It gives an arguments mismatch error. I think it does not work with special characters. Any get around to this?

Here is my code snippet:

String fileSeparator = System.getProperty("file.separator");
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Locate Java Documentation Folder");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            JTextField jtfFileLocation=new JTextField();
            jtfFileLocation.setText(chooser.getSelectedFile().getPath()+fileSeparator);
            String filePath=jtfFileLocation.getText();
            filePath.replaceAll("\\", "\\\\");
            System.out.println(filePath);
        } else {

        }
user1515601
  • 3
  • 1
  • 4

2 Answers2

7

You're most probably not escaping your backslashes correctly:

String newString = oldString.replace("\\", "\\\\");

One literal backslash has to be encoded by two backslash characters. Be glad that it's not a regex you're dealing with:

String newString = oldString.replaceAll("\\\\", "\\\\\\\\");
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Only the first parameter for the `replaceAll` method is a regex. The replacement would still be `"\\\\"`. – Lone nebula May 26 '13 at 14:13
  • 2
    @Lonenebula: No, the backslash is still a special character in a regex replacement string and needs to be escaped. Try it. – Tim Pietzcker May 26 '13 at 14:16
  • You are completely right. – Lone nebula May 26 '13 at 14:18
  • Thank you very much for your answer @Tim Pietzcker. Actually what I am trying to do is: I take a directry path from JFileChooser and hold its path in a string variable, and when I use that path in stream variable it gives me an error. When I hardcode the file path by replacing a single slash by double slash then my program works. Your replace method is still not replacing the single slash by double slash. Thanks much for your help – user1515601 May 26 '13 at 14:18
  • @user1515601: Can you post the code that's not working for you? – Tim Pietzcker May 26 '13 at 14:22
  • Can't post the code of whole application but can post a snippet where I take in the file path dynamically. Please see the edit of the question. – user1515601 May 26 '13 at 14:30
  • Done with that. Thanks for your answers. I needed to declare a new string variable as String variables are immutable. – user1515601 May 26 '13 at 14:42
0

Try String newString = originalString.replace("\\", "\\\\");

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289