繁体   English   中英

jfilechooser - 将目录设置为文件中的路径

[英]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.

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