[英]jfilechooser - set directory to a path in a file
我試圖通過這樣的東西(使用commons-io)在JFilechooser中設置目錄路徑:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File theDirectory = new File(fileContents);
filechooser = new JFileChooser();
fileChooser.setCurrentDirectory(theDirectory);
filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
我正在使用getCanonicalPath()來獲取路徑並寫入文件path.txt
path = file.getCanonicalPath();
我不打算把我的所有代碼放在這里,但我確信程序會在path.txt中寫入和讀取路徑。 我沒有收到任何錯誤,但每次運行程序時,它總是在我的文件夾中打開JFilechooser。我做錯了什么?
嘗試直接在構造函數中傳遞當前目錄:
filechooser = new JFileChooser(theDirectory);
如果您使用默認構造函數(即new JFileChooser()
)來查閱API :
構造一個指向用戶默認目錄的JFileChooser。 此默認值取決於操作系統。 它通常是Windows上的“My Documents”文件夾,以及Unix上用戶的主目錄。
這似乎可以解釋為什么始終打開我的文檔 ,但這不是你的問題。 實際上,您的問題在於設置當前目錄 (即setCurrentDirectory(theDirectory)
):
設置當前目錄。 傳入null會將文件選擇器設置為指向用戶的默認目錄。 此默認值取決於操作系統。 它通常是Windows上的“My Documents”文件夾,以及Unix上用戶的主目錄。 如果作為currentDirectory傳入的文件不是目錄,則該文件的父文件將用作currentDirectory。 如果父級不可遍歷,那么它將向上遍歷父樹,直到找到可遍歷的目錄,或者命中文件系統的根目錄。
話雖這么說,我會注意突出顯示的文本,因為您似乎將文件設置為當前目錄而不是目錄 。
要選擇您打開的最后一個目錄:
chooser.setCurrentDirectory(lastDirectory);
int r = chooser.showOpenDialog(new JPanel());
if (r == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getPath();
lastDirectory = chooser.getSelectedFile();
}
JFileChooser Chooser = new JFileChooser(“F:”);
在你的主類聲明
public static String dirpath=".";
private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jfc = new JFileChooser(dirpath);
dirpath =jfc.getSelectedFile().getAbsolutePath().toString();
}
如果要更改目錄,則使用System.getProperty方法
String s=System.getProperty("user.dir"); // changes directory from documents to the user current Directory;
JFileChooser jfc = new JFileChooser(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.