Par*_*nak 0 java jfilechooser path
在我的Java应用程序中,我需要使用JFileChooser选择路径.我写的代码如下:
jfChooser = new JFileChooser();
jfChooser.setCurrentDirectory(new java.io.File("."));
jfChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "+ jfChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+ jfChooser.getSelectedFile());
tfPath.setText(jfChooser.getSelectedFile().getAbsolutePath()); // the selected path set to textfield which is lated get by the program
}
else {
System.out.println("No Selection ");
}
Run Code Online (Sandbox Code Playgroud)
我正在获得正确的路径.例如,这里我得到的路径(在Windows操作系统中)
String choosedPath=tfPath.getText().trimm();
Run Code Online (Sandbox Code Playgroud)
现在实际上我想以编程方式在给定路径(即newfolder目录中)上创建另一个目录.
为此,我有新的目录名称"newdir",因此传递给File构造函数以创建此目录的字符串如下所示:
File createFolder = new File("choosedPath"+"\\"+"newdir");
Run Code Online (Sandbox Code Playgroud)
现在问题是我的应用程序可能在Windows上运行或者可能在Linux上运行,因此文件路径分隔符会有所不同(例如,对于Windows为'/',对于linux为'\')
我如何克服这个问题,以便根据操作系统获得路径中的propper斜杠?
new File(choosedPath, "newDir");
平台相关文件分隔符将自动选择.
您也可以使用File.separator依赖于平台的分隔符来构造字符串,但是您将以比第一个解决方案更多的代码结束.
| 归档时间: |
|
| 查看次数: |
2242 次 |
| 最近记录: |