2017-10-16 48 views
1

我正在创建一个程序来搜索目录路径。我用JFileChooser来做到这一点很棒。这是它的代码。如何使用JFileChooser添加双反斜杠insead使用JFileChooser

JButton btnPathBrowser = new JButton("Select Database"); 
     btnPathBrowser.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       final JFileChooser fc = new JFileChooser(); 
       fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
       int response = fc.showOpenDialog(Create.this); 
       if (response == JFileChooser.APPROVE_OPTION); { 
        txtPath.setText(fc.getSelectedFile().toString()); 
        //fileName = fc.getSelectedFile().toString(); 

       } 


      } 
     }); 

现在当我运行这个时,我得到了用这种方式写的路径。 GUI showing the Path

所以你可以看到路径被一个反斜杠分开,例如C:\ User \ Folder \ Database,但是我希望它用这样的两个反斜杠分支路径。 C:\ Users \用户数据库。我试过,但得到的错误:

txtPath.setText(fc.getSelectedFile().toString().replace("\", "\\")); 

我想用这样的:

String sourceFileName    = new String(txtPath.getSelectedText()); 

我很新的这所以在我的代码正确方向的任何指针将不胜感激。

回答

0

您不需要更换任何东西。你只需要逃避字符串文字的斜线,如

String myPath = "C:\\foo\\bar"; 

即使是这样,你可以只使用独立于平台的版本

String myPath = "C:/foo/bar"; 

如果你真的需要双斜杠来代替斜线,你倒是有逃避它们(作为参数字符串常量),所以你与

String foo = bar.replace("\\", "\\\\"); // Convert one slash to two slashes 

最终此外,如果你使用replaceAll方法,采用边条r表达式作为参数,则需要双重转义。一旦字符串的正则表达式引擎文字和一次:

String foo = bar.replaceAll("\\\\", "\\\\\\\\"); // Convert one slash to two slashes 

但重申一下,在你的情况不需要双斜杠。

+0

谢谢,这已经帮了我很多! –

相关问题