[英]Getting the working directory with JFileChooser
There is a JFileChooser
dialog where a user browse to a location which contains its config file. 有一个
JFileChooser
对话框,用户可以在其中浏览到包含其配置文件的位置。 I want to get that location as the working directory however, System.getProperty("user.dir")
seems to point to the location where the application starts. 我想将该位置作为工作目录,但是
System.getProperty("user.dir")
似乎指向应用程序启动的位置。 How can I fix that? 我该如何解决?
Assume 假设
D:\netbean\projects\test
that is where the application start. 那就是应用程序启动的地方。 Then the user clicks on a button and browse to
然后,用户单击按钮并浏览到
D:\configs
The code look like 代码看起来像
File selectedFile = fc.getSelectedFile();
myTextArea.setText("Working directory is " + System.getProperty("user.dir") + "\n" );
That points to netbeans folder which is wrong in my case. 指向netbeans文件夹,在我的情况下这是错误的。
System.getProperty("user.dir")
is a system property defined at runtime that is the directory where the JVM was run from. System.getProperty("user.dir")
是在运行时定义的系统属性,该属性是运行JVM的目录。
It has no relation with the directory that contains the file chosen in a JFileChooser
. 它与包含在
JFileChooser
选择的文件的目录没有关系。
You can use the getParentFile()
method of File
to retrieve the folder that contains the file that was chosen by the user: 您可以使用
File
的getParentFile()
方法来检索包含用户选择的文件的文件夹:
File selectedFile = fc.getSelectedFile();
myTextArea.setText("Parent directory is " + selectedFile.getParentFile() + "\n" );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.