【发布时间】:2011-04-18 12:42:16
【问题描述】:
在我的 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 os 中)
String choosedPath=tfPath.getText().trimm();
现在实际上我想以编程方式在给定路径(即在 newfolder 目录内)上创建另一个目录。
为此,我有新的目录名称“newdir”,因此传递给 File 构造函数以创建此目录的字符串如下:
File createFolder = new File("choosedPath"+"\\"+"newdir");
现在的问题是我的应用程序可能在 Windows 上运行或可能在 Linux 上运行,因此根据文件路径分隔符的不同(即 Windows 的“/”和 linux 的“\”)
如何克服这个问题,以便根据操作系统在路径中获得适当的斜杠?
【问题讨论】:
-
您应该考虑查看formatting sandbox 并学习如何为您的下一个问题设置代码格式
-
在 Java 中,您可以在 windows 文件路径上使用正斜杠,java 会处理它。正如其他人所说, File.Seperator 是正确的操作系统不可知论解决方案。不过,您可以在任何地方使用正斜杠。
标签: java path jfilechooser