在我的 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 ");
}
我正在正确获取路径。例如,我在这里获取路径(在 Windows 操作系统中)
String choosedPath=tfPath.getText().trimm();
现在实际上我想以编程方式在给定路径上(即在 newfolder 目录内)创建另一个目录。
为此,我有新的目录名称“newdir”,因此传递给文件构造函数以创建此目录的字符串如下:
File createFolder = new File("choosedPath"+"\\"+"newdir");
现在的问题是我的应用程序可能在 Windows 上运行,也可能在 Linux 上运行,因此文件路径分隔符会有所不同(即“/”用于 Windows,“\”用于 Linux)
如何克服这个问题,以便根据操作系统在路径中获得正确的斜杠?
最佳答案
新文件(choosedPath, "newDir");
将自动选择依赖于平台的文件分隔符。
您也可以使用File.separator
来获取依赖于平台的分隔符来构造字符串,但您最终会得到比第一个解决方案更多的代码。
关于java - 如何根据操作系统使用 JFileChooser 在 Java 中获取正确的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5703038/