繁体   English   中英

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

[英]How to get proper path in Java using JFileChooser as per the Operating system

在我的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构造函数以创建此目录的字符串如下:

File createFolder = new File("choosedPath"+"\\"+"newdir");

现在的问题是我的应用程序可以在Windows上运行,也可以在Linux上运行,因此文件路径分隔符会有所不同(例如,对于Windows,“ /”,对于Linux,“ \\”)

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

new File(choosedPath, "newDir");

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

您也可以使用File.separator来获取依赖于平台的分隔符来构造字符串,但最终将获得比第一个解决方案更多的代码。

使用File.separator代替/\\

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM