簡體   English   中英

使用JFileChooser獲取工作目錄

[英]Getting the working directory with JFileChooser

有一個JFileChooser對話框,用戶可以在其中瀏覽到包含其配置文件的位置。 我想將該位置作為工作目錄,但是System.getProperty("user.dir")似乎指向應用程序啟動的位置。 我該如何解決?

假設

 D:\netbean\projects\test

那就是應用程序啟動的地方。 然后,用戶單擊按鈕並瀏覽到

 D:\configs

代碼看起來像

File selectedFile = fc.getSelectedFile();
myTextArea.setText("Working directory is " + System.getProperty("user.dir") + "\n" );

指向netbeans文件夾,在我的情況下這是錯誤的。

System.getProperty("user.dir")是在運行時定義的系統屬性,該屬性是運行JVM的目錄。
它與包含在JFileChooser選擇的文件的目錄沒有關系。

您可以使用FilegetParentFile()方法來檢索包含用戶選擇的文件的文件夾:

File selectedFile = fc.getSelectedFile();
myTextArea.setText("Parent directory is " + selectedFile.getParentFile() + "\n" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM