如何根据操作系统使用JFileChooser在Java中获得正确的路径

如何根据操作系统使用JFileChooser在Java中获得正确的路径,java,path,jfilechooser,Java,Path,Jfilechooser,在Java应用程序中,我需要使用JFileChooser选择路径。我写的代码如下: jfChooser = new JFileChooser(); jfChooser.setCurrentDirectory(new java.io.File(".")); jfChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (jfChooser.showOpenDialog(this) == JFileChooser.APPROV

在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 ");
}
File createFolder = new File("choosedPath"+"\\"+"newdir");
我正在正确获取路径。例如,我正在获取路径(在Windows操作系统中)

现在,实际上我想以编程方式在给定路径(即newfolder目录内)上创建另一个目录

为此,我有了新的目录名“newdir”,因此传递给文件构造函数用于创建此目录的字符串如下所示:

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 ");
}
File createFolder = new File("choosedPath"+"\\"+"newdir");
现在的问题是,我的应用程序可能在windows上运行,也可能在Linux上运行,因此根据文件路径分隔符的不同(即windows的“/”和Linux的“\”)

如何克服此问题,以便根据操作系统在路径中获得正确的斜杠?

使用而不是
/
\
新文件(选择路径,“newDir”)

将自动选择平台相关的文件分隔符


<>你也可以使用<代码>文件.Stule来获得与平台相关的分隔符来构造字符串,但是你将结束的代码比第一个解决方案多。

你应该考虑检查并学习如何为java下一个问题编写代码。你可以在Windows文件路径上使用前斜杠,java会处理它。正如其他人所说,File.separator是正确的OS agnositc解决方案。不过,你可以在任何地方使用正斜杠。